From a9c862f4890009affcab6330ccae62ace0f405e9 Mon Sep 17 00:00:00 2001 From: Carolina <79524656+carochacs@users.noreply.github.com> Date: Sun, 2 Aug 2026 14:27:28 -0600 Subject: [PATCH 01/12] Fix: status check reported ready before models finished loading (#4) ls_status() treated any HTTP 200 from /health as "alignment server ready", but the demucs-server responds 200 with status:"ok" as soon as the process is up -- well before whisperx (needed for /align's VAD-anchored windows) finishes downloading/loading. During that window /health's own `warmup` block already reports e.g. `whisperx: "downloading"`. This showed a green "Alignment server ready" notice while a request would still hit the server mid-warmup, then fail with a confusing "Cannot connect to alignment server" the moment the user actually clicked Align -- despite the ready notice being visible seconds earlier. ls_status() now inspects /health's `warmup.whisperx` field and only reports available:true once it's "ready", surfacing an accurate "still loading" reason otherwise. Per-language aligners load lazily on demand and are not gated on here. Co-authored-by: Claude Haiku 4.5 --- routes.py | 33 +++++++++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/routes.py b/routes.py index f27a3c4..de39999 100644 --- a/routes.py +++ b/routes.py @@ -96,16 +96,41 @@ def setup(app: FastAPI, context: dict): @app.get("/api/plugins/lyrics_sync/status") def ls_status(): - """Check if alignment server is reachable.""" + """Check if the alignment server is reachable AND actually ready to + align — not just that /health returns 200. + + The demucs-server's /health responds 200 with `status: "ok"` as soon + as the process is up, well before its models finish loading — during + that window its `warmup` block reports fields like `whisperx: + "downloading"`. Treating any 200 as "ready" (the previous behavior) + showed a green "Alignment server ready" notice while a request would + still hit the server mid-warmup, surfacing as a confusing + "Cannot connect to alignment server" once the user actually clicked + Align. `/align` needs whisperx (transcription, used for VAD-anchored + alignment windows — see the demucs-server's own /align docs) loaded + first; per-language aligners load lazily on demand and are not + gated on here. + """ url = _get_demucs_server_url() if not url: return {"available": False, "reason": "No demucs server configured"} try: import requests resp = requests.get(f"{url}/health", timeout=5) - if resp.status_code == 200: - return {"available": True, "server_url": url} - return {"available": False, "reason": f"Server returned {resp.status_code}"} + if resp.status_code != 200: + return {"available": False, "reason": f"Server returned {resp.status_code}"} + body = resp.json() + warmup = body.get("warmup") or {} + whisperx_state = warmup.get("whisperx") + if whisperx_state != "ready": + return { + "available": False, + "reason": ( + f"Alignment model still loading ({whisperx_state or 'unknown'}) " + "— try again in a moment." + ), + } + return {"available": True, "server_url": url} except Exception as e: return {"available": False, "reason": str(e)} From 581700f089c29d9ba4ca1006926d364c02a35ab1 Mon Sep 17 00:00:00 2001 From: Carolina <79524656+carochacs@users.noreply.github.com> Date: Sun, 2 Aug 2026 14:43:02 -0600 Subject: [PATCH 02/12] Fix: saved lyrics never carried line-break markers (#3) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Fix: saved lyrics never carried line-break markers ls_save() wrote each segment's plain text straight into lyrics.json's `w` field, but the sloppak-spec line-wrap convention (docs/sloppak-hand-editing.md §Lyrics) requires a trailing "+" on the last syllable/word of every line — that's the only signal renderers (e.g. the Lyrics Karaoke plugin's syllableText()) use to know where to wrap. With it never written, saved lyrics always rendered as one unbroken line regardless of granularity. - screen.js: lsSave() now sends the selected granularity alongside segments. - routes.py: ls_save() appends "+" to the line-ending entry of each line — every entry for 'line' granularity (each segment already IS a whole line, per the align server's own docs), or the entry immediately before a `new_line: true` segment (word/syllable granularity, where the align server marks the FIRST entry of each line instead of the last). Co-Authored-By: Claude Haiku 4.5 * Group preview rows by input line for word/syllable granularity _lsRenderPreview() rendered one row per individual word/syllable segment, with only a thin divider between line groups -- so the preview didn't read like the lyrics the user actually typed. Groups consecutive segments back into one row per original input line, using the same new_line boundary the save-time fix (previous commit) already relies on. Co-Authored-By: Claude Haiku 4.5 --------- Co-authored-by: Claude Haiku 4.5 --- routes.py | 29 +++++++++++++++++++++++++---- screen.js | 37 +++++++++++++++++++++++++++---------- 2 files changed, 52 insertions(+), 14 deletions(-) diff --git a/routes.py b/routes.py index de39999..85aa51d 100644 --- a/routes.py +++ b/routes.py @@ -238,13 +238,14 @@ def ls_export(data: dict): def ls_save(data: dict): """Save synced lyrics into the sloppak manifest for playback display. - Expects: {"filename": str, "segments": [...]} + Expects: {"filename": str, "segments": [...], "granularity": str?} Writes a lyrics JSON file and updates the sloppak manifest. """ import sloppak as sloppak_mod filename = data.get("filename", "") segments = data.get("segments", []) + granularity = data.get("granularity", "line") if not filename or not segments: return JSONResponse({"error": "filename and segments required"}, 400) @@ -261,13 +262,33 @@ def ls_save(data: dict): # Convert alignment segments to the sloppak lyrics format: # [{"t": time, "d": duration, "w": word}, ...] - # For line-level: each segment becomes one entry with the full line as "w" + # + # A trailing "+" on `w` is the sloppak-spec line-break marker (docs/ + # sloppak-hand-editing.md §Lyrics) — the renderer wraps to a new line + # right after a syllable/word ending in "+". Without it every song + # renders as one unbroken line, since nothing else in lyrics.json + # carries line-boundary information. + # + # `line` granularity: the /align server returns one segment per + # line (no `new_line` field — see the demucs-server's own /align + # docs), so every entry here already *is* a whole line and gets "+". + # `word`/`syllable` granularity: the server flags the FIRST entry of + # each line with `new_line: true`; the line-ending entry is instead + # the one immediately BEFORE that (or the very last segment overall). lyrics_data = [] - for seg in segments: + for i, seg in enumerate(segments): + text = seg["text"] + is_line_end = ( + granularity == "line" + or i == len(segments) - 1 + or bool(segments[i + 1].get("new_line")) + ) + if is_line_end and not text.endswith("+"): + text = text + "+" lyrics_data.append({ "t": round(seg["start"], 3), "d": round(seg["end"] - seg["start"], 3), - "w": seg["text"], + "w": text, }) # Write lyrics JSON file diff --git a/screen.js b/screen.js index 6003eed..10cea24 100644 --- a/screen.js +++ b/screen.js @@ -179,21 +179,37 @@ function _lsFormatTime(seconds) { return `${String(m).padStart(2, '0')}:${s}`; } +function _lsGroupSegmentsByLine(segments) { + // word/syllable granularity returns one segment per word/syllable, with + // `new_line: true` on the first entry of each ORIGINAL input line (see + // the demucs-server's /align docs). Re-group them back into one chunk + // per line so the preview reads the way the lyrics were typed, instead + // of one row per individual word. + const lines = []; + for (const seg of segments) { + if (seg.new_line || lines.length === 0) { + lines.push({ start: seg.start, words: [seg.text] }); + } else { + lines[lines.length - 1].words.push(seg.text); + } + } + return lines.map(l => ({ start: l.start, text: l.words.join(' ') })); +} + function _lsRenderPreview(segments) { const container = document.getElementById('ls-preview-lines'); const granularity = _lsGetGranularity(); - // All modes: each entry on its own row with visible timestamp - // Word and syllable get a separator between phrase groups - container.innerHTML = segments.map((seg, i) => { - const separator = (granularity !== 'line' && seg.new_line && i > 0) - ? '
' : ''; - return separator + ` + // 'line' granularity: each segment already IS a whole input line. + // 'word'/'syllable': re-group into one row per line so chunks line up + // with how the lyrics were typed, rather than one row per token. + const rows = granularity === 'line' ? segments : _lsGroupSegmentsByLine(segments); + + container.innerHTML = rows.map((row) => `
- [${_lsFormatTime(seg.start)}] - ${esc(seg.text)} -
`; - }).join(''); + [${_lsFormatTime(row.start)}] + ${esc(row.text)} + `).join(''); document.getElementById('ls-preview').classList.remove('hidden'); } @@ -248,6 +264,7 @@ async function lsSave() { body: JSON.stringify({ filename: _lsSelectedFilename, segments: _lsAlignmentResult, + granularity: _lsGetGranularity(), }), }); From 326c953f63a7dfc7e4f0a3a2fda07475c9c37b0d Mon Sep 17 00:00:00 2001 From: Carolina <79524656+carochacs@users.noreply.github.com> Date: Tue, 4 Aug 2026 21:32:48 -0600 Subject: [PATCH 03/12] Add FeedBack issue workflow templates (#1) * Add FeedBack issue templates * Add FeedBack issue templates * Add FeedBack issue templates * Add FeedBack issue templates --- .github/ISSUE_TEMPLATE/bug_report.yml | 70 ++++++++++++++++++++++ .github/ISSUE_TEMPLATE/config.yml | 5 ++ .github/ISSUE_TEMPLATE/feature_request.yml | 53 ++++++++++++++++ .github/ISSUE_TEMPLATE/task.yml | 55 +++++++++++++++++ 4 files changed, 183 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.yml create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/feature_request.yml create mode 100644 .github/ISSUE_TEMPLATE/task.yml diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..4c813e5 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,70 @@ +name: Bug report +description: Report something broken or unexpectedly behaving in this FeedBack repo. +title: "[Bug]: " +labels: ["bug", "needs triage"] +body: + - type: markdown + attributes: + value: | + Use this for reproducible failures. Include the smallest chart, plugin state, or workflow that shows the issue. + - type: textarea + id: summary + attributes: + label: Summary + description: What is happening? + placeholder: Describe the problem in one or two sentences. + validations: + required: true + - type: dropdown + id: area + attributes: + label: Area + options: + - screen.js / runtime behavior + - settings.html / settings persistence + - plugin reload or idempotency + - FeedBack core integration + - performance during playback + - documentation or packaging + validations: + required: true + - type: textarea + id: steps + attributes: + label: Steps to reproduce + description: What should someone do to see the issue? + placeholder: | + 1. Open FeedBack... + 2. Enable/open... + 3. Play/import/change... + 4. See... + validations: + required: true + - type: textarea + id: expected + attributes: + label: Expected behavior + validations: + required: true + - type: textarea + id: actual + attributes: + label: Actual behavior + validations: + required: true + - type: textarea + id: validation + attributes: + label: Useful validation + description: What should be checked when this is fixed? + placeholder: Reload the plugin, open it from FeedBack, test during playback, and check console errors. + - type: input + id: environment + attributes: + label: Environment + placeholder: Browser/OS, FeedBack version or commit, plugin version, Docker image, etc. + - type: textarea + id: notes + attributes: + label: Additional notes + description: Logs, screenshots, chart files, console output, or related PRs/issues. diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..83f1aaf --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: Roadmap or planning question + url: https://github.com/orgs/get-flashbacks/projects + about: Use the relevant GitHub Project board for roadmap-level planning when available. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..8fb62a7 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,53 @@ +name: Feature request +description: Suggest a new capability or workflow improvement. +title: "[Feature]: " +labels: ["enhancement", "needs triage"] +body: + - type: textarea + id: problem + attributes: + label: User problem or opportunity + description: What workflow gap does this solve? + placeholder: When practicing or authoring in FeedBack, I want... + validations: + required: true + - type: dropdown + id: area + attributes: + label: Area + options: + - screen.js / runtime behavior + - settings.html / settings persistence + - plugin reload or idempotency + - FeedBack core integration + - performance during playback + - documentation or packaging + validations: + required: true + - type: textarea + id: proposal + attributes: + label: Proposed behavior + description: What should change from the user's perspective? + validations: + required: true + - type: textarea + id: implementation_notes + attributes: + label: Implementation notes + description: Mention relevant files, plugin lifecycle concerns, API/data format changes, or performance risks. + - type: textarea + id: acceptance + attributes: + label: Acceptance criteria + description: What must be true for this to be considered done? + placeholder: | + - [ ] The user can... + - [ ] The change survives reload/reopen... + - [ ] No console/server errors appear... + validations: + required: true + - type: textarea + id: references + attributes: + label: References or mockups diff --git a/.github/ISSUE_TEMPLATE/task.yml b/.github/ISSUE_TEMPLATE/task.yml new file mode 100644 index 0000000..57e7e0e --- /dev/null +++ b/.github/ISSUE_TEMPLATE/task.yml @@ -0,0 +1,55 @@ +name: Task or improvement +description: Track cleanup, refactors, documentation, research, or non-bug work. +title: "[Task]: " +labels: ["task", "needs triage"] +body: + - type: textarea + id: goal + attributes: + label: Goal + description: What should be accomplished? + validations: + required: true + - type: dropdown + id: area + attributes: + label: Area + options: + - screen.js / runtime behavior + - settings.html / settings persistence + - plugin reload or idempotency + - FeedBack core integration + - performance during playback + - documentation or packaging + validations: + required: true + - type: textarea + id: scope + attributes: + label: Scope + description: What is included, and what is intentionally out of scope? + - type: textarea + id: checklist + attributes: + label: Checklist + description: Break the work into concrete steps. + placeholder: | + - [ ] ... + - [ ] ... + validations: + required: true + - type: dropdown + id: priority + attributes: + label: Priority + options: + - low + - medium + - high + validations: + required: true + - type: textarea + id: validation + attributes: + label: Validation + placeholder: Reload the plugin, open it from FeedBack, test during playback, and check console errors. From 526e5093584449f5bbc2898274beaa1d82363e60 Mon Sep 17 00:00:00 2001 From: Carolina <79524656+carochacs@users.noreply.github.com> Date: Wed, 5 Aug 2026 22:45:29 -0600 Subject: [PATCH 04/12] Fix path traversal in filename-bound routes and attribute-context XSS in search results (#5) - routes.py: /align and /save built filesystem paths as `dlc / filename` with no containment check. A `filename` containing `..` traversal or an absolute path (which silently discards `dlc` under Path's `/` operator) let a request read/write files outside the configured DLC folder, as long as the target existed and was named *.sloppak/*.feedpak. Added `_safe_dlc_path()`, mirroring core's lib/dlc_paths._resolve_dlc_path containment check, and route both filename-bound handlers through it. - screen.js: lsSearchSongs() spliced song title/artist into an inline onclick="" attribute using esc(), which only escapes <, >, & for text-node use and does not escape quotes. A title/artist containing a `"` broke out of the onclick attribute (esc() output is also nested inside a single-quoted JS string literal, a second unescaped context), allowing arbitrary attribute/markup injection. Song metadata is untrusted (GP/MusicXML import tags, manifest.json, MusicBrainz enrichment). Rebuilt the row via createElement/textContent with an addEventListener closure instead of a serialized attribute string. Co-authored-by: Claude --- routes.py | 42 +++++++++++++++++++++++++++++++++++++++--- screen.js | 46 ++++++++++++++++++++++++++++++++++------------ 2 files changed, 73 insertions(+), 15 deletions(-) diff --git a/routes.py b/routes.py index 85aa51d..19e42b4 100644 --- a/routes.py +++ b/routes.py @@ -2,7 +2,7 @@ import json import os -from pathlib import Path +from pathlib import Path, PurePosixPath, PureWindowsPath from fastapi import FastAPI from fastapi.responses import JSONResponse, Response @@ -13,6 +13,38 @@ SLOPPAK_CACHE_DIR = None +def _safe_dlc_path(dlc: Path, filename: str) -> Path | None: + """Resolve `filename` under `dlc` and refuse anything that escapes it. + + `filename` arrives straight from a JSON request body, so it can contain + `..` traversal segments or be an absolute path — `dlc / filename` + discards `dlc` entirely when `filename` is absolute. Without this guard + `_find_vocals_stem`/`ls_save` would read/write files anywhere on disk + that happens to be named `*.sloppak`/`*.feedpak`, not just inside the + configured DLC folder. Mirrors the containment check core's + `lib/dlc_paths._resolve_dlc_path` applies for its own filename-bound + handlers (lexical normalization, not symlink-following, so a DLC folder + reached through a mounted junction still resolves). + """ + if not filename: + return None + safe = filename.replace("\\", "/") + if "\x00" in safe: + return None + if (PurePosixPath(safe).is_absolute() + or PureWindowsPath(safe).is_absolute() + or PureWindowsPath(safe).drive): + return None + try: + root = dlc.resolve() + candidate = Path(os.path.normpath(root / safe)) + if not candidate.is_relative_to(root): + return None + except (ValueError, OSError): + return None + return candidate + + def _get_demucs_server_url() -> str | None: """Get the configured demucs server URL from config.json.""" config_file = _config_dir / "config.json" @@ -35,7 +67,9 @@ def _find_vocals_stem(filename: str) -> Path | None: if not dlc: return None - song_path = dlc / filename + song_path = _safe_dlc_path(dlc, filename) + if song_path is None: + return None if not sloppak_mod.is_sloppak(song_path): return None @@ -254,7 +288,9 @@ def ls_save(data: dict): if not dlc: return JSONResponse({"error": "DLC folder not configured"}, 400) - song_path = dlc / filename + song_path = _safe_dlc_path(dlc, filename) + if song_path is None: + return JSONResponse({"error": "Invalid filename"}, 400) if not sloppak_mod.is_sloppak(song_path): return JSONResponse({"error": "Not a sloppak file"}, 400) diff --git a/screen.js b/screen.js index 10cea24..0f1f9c4 100644 --- a/screen.js +++ b/screen.js @@ -51,20 +51,42 @@ async function lsSearchSongs() { return; } - container.innerHTML = withStems.map(s => ` -
-
- ${esc(s.title)} - ${esc(s.artist)} -
- ${s.stem_count} stems -
- `).join(''); + // Built with createElement + textContent (not an interpolated onclick="") + // string: `esc()` only escapes <, >, & for text-node use — it does not + // escape quotes, so splicing song title/artist into an HTML attribute + // (further nested inside a JS string literal) let a title/artist + // containing a `"` or `'` break out and inject arbitrary attributes/ + // markup. Song metadata comes from imported files (GP/MusicXML tags, + // manifest.json, MusicBrainz enrichment) so it isn't trusted input. + container.innerHTML = ''; + for (const s of withStems) { + const row = document.createElement('div'); + row.className = 'flex items-center gap-3 py-2 px-3 rounded-lg hover:bg-dark-700/50 transition cursor-pointer'; + row.addEventListener('click', () => lsSelectSong(s.filename, s.title, s.artist)); + + const info = document.createElement('div'); + info.className = 'flex-1 min-w-0'; + const titleEl = document.createElement('span'); + titleEl.className = 'text-sm text-white'; + titleEl.textContent = s.title; + const artistEl = document.createElement('span'); + artistEl.className = 'text-xs text-gray-500 ml-2'; + artistEl.textContent = s.artist; + info.appendChild(titleEl); + info.appendChild(artistEl); + + const stemsEl = document.createElement('span'); + stemsEl.className = 'text-xs text-gray-600'; + stemsEl.textContent = `${s.stem_count} stems`; + + row.appendChild(info); + row.appendChild(stemsEl); + container.appendChild(row); + } } -function lsSelectSong(encodedFilename, title, artist) { - _lsSelectedFilename = decodeURIComponent(encodedFilename); +function lsSelectSong(filename, title, artist) { + _lsSelectedFilename = filename; _lsSelectedTitle = title; _lsSelectedArtist = artist; From 3bdf7d0bad52d5065e54e24223235fbec7a66328 Mon Sep 17 00:00:00 2001 From: Carolina <79524656+carochacs@users.noreply.github.com> Date: Wed, 5 Aug 2026 22:54:39 -0600 Subject: [PATCH 05/12] Bump version for path-traversal / XSS fixes (#6) Ecosystem versioning convention (feedBack-plugin-spec best practices, rule 4): PATCH bump for a fix. Covers the two security fixes already pushed to this branch. No CHANGELOG.md exists in this repo to update. --- plugin.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin.json b/plugin.json index 9e558f4..9690b00 100644 --- a/plugin.json +++ b/plugin.json @@ -1,7 +1,7 @@ { "id": "lyrics_sync", "name": "Lyrics Sync", - "version": "1.0.0", + "version": "1.0.1", "private": false, "nav": { "label": "Lyrics Sync", From d5125097e77ecca650b52000c198f34bae003507 Mon Sep 17 00:00:00 2001 From: Carolina <79524656+carochacs@users.noreply.github.com> Date: Thu, 6 Aug 2026 18:12:15 -0600 Subject: [PATCH 06/12] Add `pullfrog.yml` workflow --- .github/workflows/pullfrog.yml | 67 ++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 .github/workflows/pullfrog.yml diff --git a/.github/workflows/pullfrog.yml b/.github/workflows/pullfrog.yml new file mode 100644 index 0000000..b34af7e --- /dev/null +++ b/.github/workflows/pullfrog.yml @@ -0,0 +1,67 @@ +# PULLFROG ACTION — DO NOT EDIT EXCEPT WHERE INDICATED +name: Pullfrog +run-name: ${{ inputs.name || github.workflow }} +on: + workflow_dispatch: + inputs: + prompt: + type: string + description: Agent prompt + name: + type: string + description: Run name + +permissions: + contents: read + +jobs: + pullfrog: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + steps: + - name: Checkout code + uses: actions/checkout@v6 + with: + fetch-depth: 1 + - name: Run agent + uses: pullfrog/pullfrog@v0 + with: + prompt: ${{ inputs.prompt }} + env: + # add at least one provider API key + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + CLAUDE_CODE_OAUTH_TOKEN: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} + GOOGLE_GENERATIVE_AI_API_KEY: + ${{ secrets.GOOGLE_GENERATIVE_AI_API_KEY }} + GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} + XAI_API_KEY: ${{ secrets.XAI_API_KEY }} + DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY }} + MOONSHOT_API_KEY: ${{ secrets.MOONSHOT_API_KEY }} + OPENROUTER_API_KEY: ${{ secrets.OPENROUTER_API_KEY }} + OPENCODE_API_KEY: ${{ secrets.OPENCODE_API_KEY }} + + # for Amazon Bedrock (https://docs.pullfrog.com/bedrock) + # AWS_BEARER_TOKEN_BEDROCK: ${{ secrets.AWS_BEARER_TOKEN_BEDROCK }} + # AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} + # AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + # AWS_REGION: us-east-1 + # BEDROCK_MODEL_ID: + + # for Google Vertex AI (https://docs.pullfrog.com/vertex) + # VERTEX_SERVICE_ACCOUNT_JSON: >- + # ${{ secrets.VERTEX_SERVICE_ACCOUNT_JSON }} + # GOOGLE_CLOUD_PROJECT: my-project + # VERTEX_LOCATION: global + # VERTEX_MODEL_ID: + + # for any OpenAI-compatible endpoint — LiteLLM, Cloudflare AI Gateway, + # self-hosted vLLM (https://docs.pullfrog.com/openai-compatible) + # OPENAI_COMPATIBLE_BASE_URL: https://litellm.example.com/v1 + # OPENAI_COMPATIBLE_API_KEY: ${{ secrets.OPENAI_COMPATIBLE_API_KEY }} + # OPENAI_COMPATIBLE_MODEL: + # both limits are required — set them to the real limits of that model + # OPENAI_COMPATIBLE_CONTEXT: "128000" + # OPENAI_COMPATIBLE_MAX_OUTPUT: "16384" From 8165c990b3efb566136e3563c5a2c7fdf2045f62 Mon Sep 17 00:00:00 2001 From: Carolina <79524656+carochacs@users.noreply.github.com> Date: Tue, 18 Aug 2026 22:18:08 -0600 Subject: [PATCH 07/12] fix: escape Content-Disposition filenames and guard malformed align responses (#10) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: escape Content-Disposition filenames and guard malformed align responses - ls_export now quote-escapes title/artist before embedding them in the Content-Disposition filename param, and adds an RFC 5987 filename*= fallback, so an embedded quote can't corrupt/break out of the header. - ls_align now wraps resp.json() in a try/except so a non-JSON response from the configured align server returns a clean 502 instead of an unhandled 500. Fixes #7, #8 * fix: clarify no-op backslash escape in ls_export filename header pullfrog review on PR #10 flagged that the \\ -> \\\\ replacement in ascii_name is a no-op today (safe_name already stripped \\ above) — harmless but confusing without context. Added a one-line comment explaining it's a belt-and-suspenders guard for if that stripping ever changes, rather than dead code. --------- Co-authored-by: Claude --- plugin.json | 2 +- routes.py | 22 ++++++++++++++++++++-- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/plugin.json b/plugin.json index 9690b00..bc5f9d0 100644 --- a/plugin.json +++ b/plugin.json @@ -1,7 +1,7 @@ { "id": "lyrics_sync", "name": "Lyrics Sync", - "version": "1.0.1", + "version": "1.0.2", "private": false, "nav": { "label": "Lyrics Sync", diff --git a/routes.py b/routes.py index 19e42b4..a70dff7 100644 --- a/routes.py +++ b/routes.py @@ -3,6 +3,7 @@ import json import os from pathlib import Path, PurePosixPath, PureWindowsPath +from urllib.parse import quote from fastapi import FastAPI from fastapi.responses import JSONResponse, Response @@ -219,7 +220,13 @@ def ls_align(data: dict): 502, ) - result = resp.json() + try: + result = resp.json() + except ValueError: + return JSONResponse( + {"error": "Alignment server returned a malformed response"}, + 502, + ) if "error" in result: return JSONResponse( {"error": f"Alignment failed: {result['error']}"}, @@ -260,11 +267,22 @@ def ls_export(data: dict): safe_name = f"{artist} - {title}".strip(" -") or "lyrics" safe_name = safe_name.replace("/", "_").replace("\\", "_") + # Quote-escape for the legacy `filename=` fallback, and provide an + # RFC 5987 `filename*=` form so non-ASCII / quote characters in + # title-artist can't corrupt or break out of the header value. + # The `\` escape is a no-op today (safe_name already stripped `\` + # above) but guards this line if that stripping ever changes. + ascii_name = safe_name.replace("\\", "\\\\").replace('"', '\\"') + encoded_name = quote(f"{safe_name}.lrc", safe="") + return Response( content=lrc, media_type="text/plain", headers={ - "Content-Disposition": f'attachment; filename="{safe_name}.lrc"', + "Content-Disposition": ( + f'attachment; filename="{ascii_name}.lrc"; ' + f"filename*=UTF-8''{encoded_name}" + ), }, ) From fdd3a30c0e805e8d4556668cd1e5a4fabe757111 Mon Sep 17 00:00:00 2001 From: Carolina <79524656+carochacs@users.noreply.github.com> Date: Fri, 28 Aug 2026 09:59:58 -0600 Subject: [PATCH 08/12] Add manual lyrics editor: tap-to-time and waveform drag-editing (#9) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add manual lyrics editor: tap-to-time and waveform drag-editing Both existing lyrics plugins were generate-only (Whisper align, save) with no way to fix the ~10% alignment gets wrong or author lyrics for a song with no vocals stem. Adds a hand-editing surface: tap-to-time, drag/resize syllable blocks over a client-decoded waveform, text seeding with manual syllable splits, and loading/correcting a song's existing lyrics via a new GET /lyrics endpoint. Saves go through a new POST /save-lyrics, validated server-side the same way the sloppak loader filters lyrics.json on read. Also fixes a real bug in the existing align-based /save: it wrote lyrics.json into the extraction cache for zip-form sloppaks instead of the distributable .sloppak file, so edits were silently lost whenever the cache was invalidated. Both save paths now funnel through one _persist_lyrics helper (ported from lyrics_karaoke's mature zip-repack pattern) that rewrites directory-form packs in place and re-zips zip-form packs with a one-time .bak. Hardens _find_vocals_stem against a manifest-controlled path escaping the pack directory, matching the containment check already applied to request-supplied filenames. * Fix three data-loss bugs Pullfrog's review caught in the manual editor - _lsAlignmentResult wasn't bound to the song it was computed for: align song A, select song B, then "Edit Manually"/"Save to Song" would persist A's alignment into B. Clear it (and hide the preview) whenever the selected song changes. - Re-opening the editor, or navigating away from the screen, silently discarded unsaved tap-to-time/drag edits with no warning. Added dirty tracking (generation + history-index pair, so undoing back to exactly the loaded/saved snapshot correctly reports clean again) and a confirm() guard in lsOpenEditor's reopen path, lsCloseEditor, and the showScreen navigation hook. Callers that switch songs now check lsCloseEditor()'s return value and abort the switch if the user kept the editor open, rather than moving on to a new song while the editor still points at the old one. - Saving a session with only untimed syllables (text seeded via "Add", nothing tapped/dragged yet) silently posted an empty list, which the server correctly treats as "clear the track" — wiping any lyrics already saved on the song, with the seeded text already gone from the textarea and no way to recover it. Now confirms first. * Fix inaccurate docstring and add the tests the PR body claimed - ls_save_lyrics's docstring said validation matched the sloppak loader's own read-side filter. It doesn't — the loader only checks type (str / int-or-float), with no finiteness check, no d<=0 drop, no rounding. This handler is stricter, not equivalent; reworded to say so. - The original PR body described round-trip, traversal, and endpoint tests that were run ad-hoc but never committed — this repo had no tests/ directory at all. Adds tests/test_helpers.py (mirrors lyrics_karaoke's existing isolated-test convention: pure/file-IO helpers only, no dependency on core's sloppak module since that isn't available outside the feedBack host). Covers path-traversal rejection, manifest IO, and — the load-bearing case — _persist_lyrics for both directory-form and zip-form sloppaks, asserting the write lands inside the actual .zip archive rather than only the extraction cache. That's a direct regression test for the persistence bug this PR fixed. * Fix two real regressions in the dirty-tracking guard just added - lsEditInEditor's .then() ran unconditionally, so declining the "discard unsaved edits?" prompt in lsOpenEditor (or having no song selected) didn't stop it — the alignment seed still overwrote _lsEditorSyllables and reset the undo history, destroying the exact edits the user just chose to keep. lsOpenEditor now returns whether it actually (re)loaded; lsEditInEditor checks that before seeding. - The (generation, history-index) dirty scheme broke once a session crossed the 50-entry undo cap: _lsEditorPushHistory shifts the oldest snapshot out on overflow, so "index 0" after enough edits no longer means the snapshot that was actually saved — undoing back to it could report clean (skipping the discard prompt) while showing genuinely different content. Replaced with a content-based comparison (JSON-serialized snapshot vs. the live array), which doesn't depend on history-array bookkeeping surviving intact across the whole session. Both caught by Pullfrog's review of the previous fix commit. --------- Co-authored-by: Claude --- README.md | 47 +- plugin.json | 4 +- routes.py | 350 +++++++++++--- screen.html | 115 ++++- screen.js | 1014 +++++++++++++++++++++++++++++++++++++++++ tests/test_helpers.py | 223 +++++++++ 6 files changed, 1683 insertions(+), 70 deletions(-) create mode 100644 tests/test_helpers.py diff --git a/README.md b/README.md index bdcb129..3e0702e 100644 --- a/README.md +++ b/README.md @@ -1,29 +1,52 @@ # Lyrics Sync -A [Slopsmith](https://github.com/got-feedback/feedback) plugin that generates time-synced LRC lyrics files using Whisper forced alignment against isolated vocals stems. +A [feedBack](https://github.com/got-feedback/feedback) plugin for authoring and +time-aligning song lyrics: generate synced timing with Whisper forced +alignment against an isolated vocals stem, or hand-edit with tap-to-time and +waveform drag-editing. ## How it works +### AI alignment + 1. Select a sloppak song that has split stems (vocals track required) 2. Paste or upload plain text lyrics -3. The plugin sends the vocals stem to your [Slopsmith Demucs Server](https://github.com/byrongamatos/slopsmith-demucs-server) for Whisper forced alignment -4. Preview the timestamped result, then download as `.lrc` or save directly into the sloppak for playback display - -Because sloppak songs already have an isolated vocals track from Demucs separation, alignment accuracy is significantly better than aligning against a full mix. +3. The plugin sends the vocals stem to your [feedBack Demucs Server](https://github.com/byrongamatos/slopsmith-demucs-server) for Whisper forced alignment +4. Preview the timestamped result, then download as `.lrc`, save directly into the sloppak, or open it in the manual editor to fix anything alignment got wrong + +### Manual editor + +Click **Open Editor** once a song is selected — it loads that song's existing +lyrics for correction, or starts empty for authoring from scratch. Click +**Edit Manually** on an alignment preview to review/fix the result before +saving. + +- **Tap-to-time** — play the song and tap Space along with the vocal; each + tap stamps the next syllable's start time and closes the previous one's + duration, so a whole verse can be timed in one pass +- **Waveform drag-editing** — syllable blocks are laid over the stem's + waveform; drag a block to move it, drag an edge to resize it, double-click + to edit its text. Blocks snap to neighbouring edges (hold Alt to bypass) +- **Seed from text** — paste plain lyrics to create untimed syllables; mark + syllable splits within a word with `/` (e.g. `won/der/ful`) +- **A–B loop + speed control** — loop a phrase and slow playback down while + timing a tricky section +- **Undo/redo**, and a stem picker for switching between the vocals track and + the full mix ## Features -- **Line, word, and syllable granularity** — choose the level of timing precision +- **Line, word, and syllable granularity** for AI alignment — choose the level of timing precision - **Language hint** — optional language code to improve accuracy for non-English lyrics - **LRC export** — standard `[mm:ss.xx] line` format compatible with any LRC player -- **Save to song** — writes synced lyrics into the sloppak manifest so they display during playback via the lyrics toggle -- **Preview panel** — review timestamps before exporting +- **Save to song** — writes synced lyrics into the sloppak so they display during playback via the lyrics toggle. Directory-form sloppaks are rewritten in place; zip-form `.sloppak` files are re-zipped (with a one-time `.bak`) so edits land in the distributable file, not just the extraction cache +- **Preview panel** — review AI-aligned timestamps before exporting or saving +- **Manual editor** — tap-to-time, waveform drag-editing, and text seeding for authoring or correcting lyrics by hand ## Requirements -- A running [Slopsmith Demucs Server](https://github.com/byrongamatos/slopsmith-demucs-server) with the `/align` endpoint (v2+) -- The demucs server URL must be configured in Slopsmith settings -- Sloppak songs with split stems (use the Sloppak Converter plugin with Demucs splitting enabled) +- The manual editor works on any sloppak — no external service required +- AI alignment additionally needs a running [feedBack Demucs Server](https://github.com/byrongamatos/slopsmith-demucs-server) with the `/align` endpoint (v2+), configured in feedBack settings, and split stems on the song (use the Sloppak Converter plugin with Demucs splitting enabled) ## Install @@ -32,4 +55,4 @@ cd plugins git clone https://github.com/got-feedback/feedback-plugin-lyrics-sync.git lyrics_sync ``` -Restart Slopsmith and the plugin will appear in the Plugins dropdown. +Restart feedBack and the plugin will appear in the Plugins dropdown. diff --git a/plugin.json b/plugin.json index bc5f9d0..f293d90 100644 --- a/plugin.json +++ b/plugin.json @@ -1,11 +1,11 @@ { "id": "lyrics_sync", "name": "Lyrics Sync", - "version": "1.0.2", + "version": "1.1.1", "private": false, "nav": { "label": "Lyrics Sync", - "screen": "lyrics-sync" + "screen": "plugin-lyrics_sync" }, "screen": "screen.html", "script": "screen.js", diff --git a/routes.py b/routes.py index a70dff7..1b2f1b9 100644 --- a/routes.py +++ b/routes.py @@ -1,10 +1,13 @@ -"""Lyrics Sync plugin — generate time-synced LRC from plain text lyrics + vocals stem.""" +"""Lyrics Sync plugin — author, time-align, and hand-edit synced lyrics.""" import json import os +import shutil +import zipfile from pathlib import Path, PurePosixPath, PureWindowsPath from urllib.parse import quote +import yaml from fastapi import FastAPI from fastapi.responses import JSONResponse, Response @@ -20,7 +23,7 @@ def _safe_dlc_path(dlc: Path, filename: str) -> Path | None: `filename` arrives straight from a JSON request body, so it can contain `..` traversal segments or be an absolute path — `dlc / filename` discards `dlc` entirely when `filename` is absolute. Without this guard - `_find_vocals_stem`/`ls_save` would read/write files anywhere on disk + `_find_vocals_stem`/save handlers would read/write files anywhere on disk that happens to be named `*.sloppak`/`*.feedpak`, not just inside the configured DLC folder. Mirrors the containment check core's `lib/dlc_paths._resolve_dlc_path` applies for its own filename-bound @@ -46,6 +49,86 @@ def _safe_dlc_path(dlc: Path, filename: str) -> Path | None: return candidate +def _safe_source_path(source_dir: Path, rel: str) -> Path | None: + """Resolve a manifest-declared relative path under `source_dir`, + refusing anything that escapes it. + + Manifest content (`stems[].file`, `lyrics`) is untrusted — it comes from + inside a `.sloppak`/`.feedpak` package that may have been authored or + shared by someone other than the library owner. Without this check, + `source_dir / rel` has two failure modes: an absolute `rel` (e.g. + `/etc/passwd`) silently discards `source_dir` entirely (a pathlib + quirk), and a `rel` containing `..` walks out of the pack directory. + Either lets a crafted pack make this plugin read an arbitrary local + file — and for the vocals stem, upload its bytes to the configured + alignment/demucs server. + """ + if not rel: + return None + safe = str(rel).replace("\\", "/") + if "\x00" in safe: + return None + if (PurePosixPath(safe).is_absolute() + or PureWindowsPath(safe).is_absolute() + or PureWindowsPath(safe).drive): + return None + try: + root = source_dir.resolve() + candidate = Path(os.path.normpath(root / safe)) + if not candidate.is_relative_to(root): + return None + except (ValueError, OSError): + return None + return candidate + + +# ── Manifest helpers ──────────────────────────────────────────────────────── + +def _manifest_path(source_dir: Path) -> Path: + p = source_dir / "manifest.yaml" + if not p.exists(): + alt = source_dir / "manifest.yml" + if alt.exists(): + return alt + return p + + +def _read_manifest(source_dir: Path) -> dict: + mp = _manifest_path(source_dir) + return yaml.safe_load(mp.read_text(encoding="utf-8")) or {} + + +def _write_manifest(source_dir: Path, manifest: dict) -> None: + mp = _manifest_path(source_dir) + mp.write_text( + yaml.safe_dump(manifest, sort_keys=False, allow_unicode=True), + encoding="utf-8", + ) + + +def _resolve_sloppak(filename: str): + """Resolve a sloppak filename to its source dir, manifest, and zip flag. + + Returns `(source_dir, manifest, dlc_path, is_zip)` or `None` when the + target is missing or isn't a sloppak. + """ + import sloppak as sloppak_mod + + if not filename: + return None + dlc = _get_dlc_dir() if _get_dlc_dir else None + if not dlc: + return None + dlc_path = _safe_dlc_path(dlc, filename) + if dlc_path is None or not dlc_path.exists(): + return None + if not sloppak_mod.is_sloppak(dlc_path): + return None + source_dir = sloppak_mod.resolve_source_dir(filename, dlc, SLOPPAK_CACHE_DIR) + manifest = _read_manifest(source_dir) + return source_dir, manifest, dlc_path, dlc_path.is_file() + + def _get_demucs_server_url() -> str | None: """Get the configured demucs server URL from config.json.""" config_file = _config_dir / "config.json" @@ -62,30 +145,21 @@ def _get_demucs_server_url() -> str | None: def _find_vocals_stem(filename: str) -> Path | None: """Find the vocals stem file for a sloppak song.""" - import sloppak as sloppak_mod - - dlc = _get_dlc_dir() - if not dlc: - return None - - song_path = _safe_dlc_path(dlc, filename) - if song_path is None: - return None - if not sloppak_mod.is_sloppak(song_path): + resolved = _resolve_sloppak(filename) + if resolved is None: return None - - source_dir = sloppak_mod.resolve_source_dir(filename, dlc, SLOPPAK_CACHE_DIR) - manifest = sloppak_mod.load_manifest(song_path) + source_dir, manifest, _dlc_path, _is_zip = resolved for s in manifest.get("stems", []) or []: if not isinstance(s, dict): continue sid = str(s.get("id", "")).lower() sfile = str(s.get("file", "")) - if sid == "vocals" and sfile: - vocals_path = source_dir / sfile - if vocals_path.exists(): - return vocals_path + if sid != "vocals" or not sfile: + continue + vocals_path = _safe_source_path(source_dir, sfile) + if vocals_path is not None and vocals_path.exists(): + return vocals_path return None @@ -121,6 +195,66 @@ def _format_lrc_word_level(segments: list[dict]) -> str: return "\n".join(lines) + "\n" +# ── Persistence: write lyrics.json + patch manifest + re-zip ────────────────── + +def _atomic_write_json(path: Path, payload) -> None: + tmp = path.with_suffix(path.suffix + ".tmp") + tmp.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8") + tmp.replace(path) + + +def _rezip_sloppak(source_dir: Path, output_path: Path) -> None: + """Replace the zip-form sloppak with the contents of source_dir. + + Keeps a one-time `.bak` of the original next to it so a botched run + is recoverable. Writes via `.tmp` + atomic replace so a crash mid-zip + doesn't leave a half-written archive. + """ + if output_path.exists() and output_path.is_file(): + backup = output_path.with_suffix(output_path.suffix + ".bak") + if not backup.exists(): + shutil.copy2(output_path, backup) + output_path.parent.mkdir(parents=True, exist_ok=True) + tmp_zip = output_path.with_suffix(output_path.suffix + ".tmp") + if tmp_zip.exists(): + tmp_zip.unlink() + with zipfile.ZipFile(str(tmp_zip), "w", zipfile.ZIP_DEFLATED) as zf: + for f in source_dir.rglob("*"): + if f.is_file(): + zf.write(f, f.relative_to(source_dir).as_posix()) + tmp_zip.replace(output_path) + + +def _persist_lyrics( + source_dir: Path, + manifest: dict, + lyrics_data: list[dict], + dlc_path: Path, + is_zip: bool, + source: str = "user", +) -> int: + """Write `lyrics_data` to `lyrics.json`, patch the manifest, and (for + zip-form packs) re-zip so the edit reaches the distributable `.sloppak` + file rather than only the extraction cache. + + An empty `lyrics_data` list is valid — it's how a track gets cleared — + and is still written and manifest-patched like any other save. + + Returns the number of lyric entries written. + """ + _atomic_write_json(source_dir / "lyrics.json", lyrics_data) + + if manifest.get("lyrics") != "lyrics.json" or manifest.get("lyrics_source") != source: + manifest["lyrics"] = "lyrics.json" + manifest["lyrics_source"] = source + _write_manifest(source_dir, manifest) + + if is_zip: + _rezip_sloppak(source_dir, dlc_path) + + return len(lyrics_data) + + def setup(app: FastAPI, context: dict): global _config_dir, _get_dlc_dir, SLOPPAK_CACHE_DIR @@ -288,13 +422,14 @@ def ls_export(data: dict): @app.post("/api/plugins/lyrics_sync/save") def ls_save(data: dict): - """Save synced lyrics into the sloppak manifest for playback display. + """Save aligned lyrics into the sloppak for playback display. Expects: {"filename": str, "segments": [...], "granularity": str?} - Writes a lyrics JSON file and updates the sloppak manifest. + Converts Whisper alignment segments to the sloppak lyrics format and + persists via `_persist_lyrics` — directory-form packs are rewritten + in place; zip-form packs are re-zipped so the edit lands in the + distributable `.sloppak` file, not just the extraction cache. """ - import sloppak as sloppak_mod - filename = data.get("filename", "") segments = data.get("segments", []) granularity = data.get("granularity", "line") @@ -302,17 +437,10 @@ def ls_save(data: dict): if not filename or not segments: return JSONResponse({"error": "filename and segments required"}, 400) - dlc = _get_dlc_dir() - if not dlc: - return JSONResponse({"error": "DLC folder not configured"}, 400) - - song_path = _safe_dlc_path(dlc, filename) - if song_path is None: - return JSONResponse({"error": "Invalid filename"}, 400) - if not sloppak_mod.is_sloppak(song_path): - return JSONResponse({"error": "Not a sloppak file"}, 400) - - source_dir = sloppak_mod.resolve_source_dir(filename, dlc, SLOPPAK_CACHE_DIR) + resolved = _resolve_sloppak(filename) + if resolved is None: + return JSONResponse({"error": "Not a sloppak"}, 400) + source_dir, manifest, dlc_path, is_zip = resolved # Convert alignment segments to the sloppak lyrics format: # [{"t": time, "d": duration, "w": word}, ...] @@ -345,27 +473,139 @@ def ls_save(data: dict): "w": text, }) - # Write lyrics JSON file - lyrics_path = source_dir / "lyrics.json" - lyrics_path.write_text(json.dumps(lyrics_data, indent=2), encoding="utf-8") + try: + count = _persist_lyrics(source_dir, manifest, lyrics_data, dlc_path, is_zip) + except Exception as exc: # noqa: BLE001 + return JSONResponse({"error": f"Persist failed: {exc}"}, 500) + + return {"ok": True, "lyrics_count": count} - # Update manifest to reference the lyrics file - manifest_path = source_dir / "manifest.yaml" - if manifest_path.exists(): + @app.get("/api/plugins/lyrics_sync/lyrics") + def ls_get_lyrics(filename: str = ""): + """Load a sloppak's existing lyrics + audio info for the editor. + + Returns: {ok, lyrics: [{t,d,w}], source, duration, + stems: [{id, file, url}]} + """ + resolved = _resolve_sloppak(filename) + if resolved is None: + return JSONResponse({"error": "Not a sloppak"}, 400) + source_dir, manifest, _dlc_path, _is_zip = resolved + + lyrics: list[dict] = [] + rel = manifest.get("lyrics") + if rel: + p = _safe_source_path(source_dir, str(rel)) + if p is not None and p.exists(): + try: + raw = json.loads(p.read_text(encoding="utf-8")) + except Exception: + raw = None + if isinstance(raw, list): + for item in raw: + if not isinstance(item, dict): + continue + try: + t = float(item.get("t", 0.0)) + d = float(item.get("d", 0.0)) + except (TypeError, ValueError): + continue + lyrics.append({"t": t, "d": d, "w": str(item.get("w", ""))}) + + raw_source = manifest.get("lyrics_source") + source = raw_source if isinstance(raw_source, str) else "" + + # Stem URLs use the same core-served endpoint (and the same + # encoding) that the highway WebSocket hands the player — + # `/api/sloppak/{filename}/file/{rel_path}` (lib/routers/media.py). + # Building the URL here means the editor never has to duplicate + # this encoding logic client-side. + q_fn = quote(filename, safe="") + stems = [] + for s in manifest.get("stems", []) or []: + if not isinstance(s, dict): + continue + sid = str(s.get("id", "")) + sfile = str(s.get("file", "")) + if sid and sfile: + stems.append({ + "id": sid, + "file": sfile, + "url": f"/api/sloppak/{q_fn}/file/{quote(sfile)}", + }) + + duration = manifest.get("duration") + try: + duration = float(duration) if duration is not None else None + except (TypeError, ValueError): + duration = None + + return { + "ok": True, + "lyrics": lyrics, + "source": source, + "duration": duration, + "stems": stems, + } + + @app.post("/api/plugins/lyrics_sync/save-lyrics") + def ls_save_lyrics(data: dict): + """Persist hand-edited lyrics from the editor. + + Expects: {"filename": str, "lyrics": [{"t": float, "d": float, "w": str}, ...]} + + Unlike `/save` (which derives entries from Whisper alignment + segments), this takes the editor's `{t, d, w}` list verbatim — + markers ('-' join / '+' line-break) are already encoded into `w` + by the client. Validated *more strictly* than the sloppak loader's + own read-side filter (lib/sloppak.py, which only checks `w` is a + str and `t`/`d` are int/float — no finiteness check, no `d <= 0` + drop, no rounding): every entry here must have a string `w` and + finite numeric `t`/`d`; entries with `d <= 0` are dropped; the + rest are rounded and sorted by `t`. The extra strictness keeps + what a save writes well-formed rather than merely + loader-tolerated. + + An empty list is a valid save — it clears the lyrics track. + """ + filename = data.get("filename", "") + raw_lyrics = data.get("lyrics", []) + + if not filename: + return JSONResponse({"error": "filename required"}, 400) + if not isinstance(raw_lyrics, list): + return JSONResponse({"error": "lyrics must be a list"}, 400) + + import math + + lyrics_data = [] + for item in raw_lyrics: + if not isinstance(item, dict): + continue + w = item.get("w") + if not isinstance(w, str): + continue try: - import yaml - except ImportError: - # Fallback: read and patch YAML manually - text = manifest_path.read_text(encoding="utf-8") - if "lyrics:" not in text: - text = text.rstrip() + "\nlyrics: lyrics.json\n" - manifest_path.write_text(text, encoding="utf-8") - else: - manifest = yaml.safe_load(manifest_path.read_text(encoding="utf-8")) or {} - manifest["lyrics"] = "lyrics.json" - manifest_path.write_text( - yaml.dump(manifest, default_flow_style=False, allow_unicode=True), - encoding="utf-8", - ) + t = float(item.get("t")) + d = float(item.get("d")) + except (TypeError, ValueError): + continue + if not (math.isfinite(t) and math.isfinite(d)): + continue + if d <= 0: + continue + lyrics_data.append({"t": round(t, 3), "d": round(d, 3), "w": w}) + + lyrics_data.sort(key=lambda e: e["t"]) + + resolved = _resolve_sloppak(filename) + if resolved is None: + return JSONResponse({"error": "Not a sloppak"}, 400) + source_dir, manifest, dlc_path, is_zip = resolved + + try: + count = _persist_lyrics(source_dir, manifest, lyrics_data, dlc_path, is_zip) + except Exception as exc: # noqa: BLE001 + return JSONResponse({"error": f"Persist failed: {exc}"}, 500) - return {"ok": True, "lyrics_count": len(lyrics_data)} + return {"ok": True, "lyrics_count": count} diff --git a/screen.html b/screen.html index ef2fdda..0c3b151 100644 --- a/screen.html +++ b/screen.html @@ -3,7 +3,7 @@ Back

Lyrics Sync

-

Generate time-synced lyrics from plain text using AI forced alignment against the vocals stem.

+

Author and time-align song lyrics — generate synced timing with AI forced alignment, or hand-edit with tap-to-time and waveform drag-editing.

@@ -86,7 +86,120 @@

Preview

+ + + +
+
+ +

Load the selected song's existing lyrics, tap along to time a song from + scratch, or drag syllable blocks on the waveform to fix timings.

+
+ +
+ + diff --git a/screen.js b/screen.js index 0f1f9c4..cb59239 100644 --- a/screen.js +++ b/screen.js @@ -86,6 +86,20 @@ async function lsSearchSongs() { } function lsSelectSong(filename, title, artist) { + // Editor state (loaded lyrics, undo history, audio src) belongs to + // whatever song was selected when it was opened — switching songs + // without closing first would let a save land on the wrong file. + // lsCloseEditor() may prompt and refuse to close (unsaved edits); if + // it does, abort the switch too, or the editor would stay open while + // every other bit of state below moves on to the new song. + if (typeof lsCloseEditor === 'function' && !lsCloseEditor()) return; + + // Same hazard for the align/preview flow: _lsAlignmentResult isn't + // bound to the song it was computed for, so leaving it live across a + // song switch would let "Edit Manually" / "Save to Song" persist the + // PREVIOUS song's alignment into the newly selected one. + _lsClearAlignmentResult(); + _lsSelectedFilename = filename; _lsSelectedTitle = title; _lsSelectedArtist = artist; @@ -95,15 +109,25 @@ function lsSelectSong(filename, title, artist) { document.getElementById('ls-selected-song').classList.remove('hidden'); document.getElementById('ls-selected-label').textContent = `${title} — ${artist}`; _lsUpdateAlignBtn(); + if (typeof _lsUpdateOpenEditorBtn === 'function') _lsUpdateOpenEditorBtn(); } function lsClearSong() { + if (typeof lsCloseEditor === 'function' && !lsCloseEditor()) return; + _lsClearAlignmentResult(); + _lsSelectedFilename = null; _lsSelectedTitle = ""; _lsSelectedArtist = ""; document.getElementById('ls-selected-song').classList.add('hidden'); document.getElementById('ls-selected-label').textContent = ''; _lsUpdateAlignBtn(); + if (typeof _lsUpdateOpenEditorBtn === 'function') _lsUpdateOpenEditorBtn(); +} + +function _lsClearAlignmentResult() { + _lsAlignmentResult = null; + document.getElementById('ls-preview')?.classList.add('hidden'); } // ── Lyrics input ───────────────────────────────────────────────────────── @@ -306,6 +330,954 @@ async function lsSave() { } } +// ── Manual editor ──────────────────────────────────────────────────────── +// +// A hand-editing surface for the same {t, d, w} syllable list `/save` +// writes, layered on the alignment flow above rather than replacing it: +// "Edit Manually" in the align preview seeds the editor from a fresh +// alignment result, and "Open Editor" loads whatever's already saved on +// the selected song (via GET /lyrics) for correction. Model is a flat +// array in render order with the wire markers decoded into booleans: +// +// { w: "Hel", t: 12.34, d: 0.18, join: true, brk: false } +// // join → trailing "-" (joins next syllable) brk → trailing "+" (line break) +// +// join/brk are mutually exclusive — a line-ending syllable can't also +// join the next word — and are re-encoded as a single trailing suffix on +// save, matching the exactly-one-marker contract core's sylText() (static/ +// js/highway-draw.js) decodes on read. + +let _lsEditorSyllables = []; // [{w, t, d, join, brk}], t/d null = untimed +let _lsEditorSelectedIndex = -1; +let _lsEditorHistory = []; // snapshot stack of _lsEditorSyllables +let _lsEditorHistoryIndex = -1; +// Dirty tracking: a serialized snapshot of _lsEditorSyllables as of the +// last successful load/save, compared by VALUE against the live array. +// Deliberately content-based rather than tracking a history index — +// _lsEditorPushHistory caps the undo stack at 50 entries and shifts the +// oldest snapshot out on overflow, so "index 0" doesn't reliably mean the +// same thing across a long editing session; comparing content sidesteps +// that entirely (undoing back to exactly the saved state reports clean +// again regardless of how much history got evicted in between). +let _lsEditorSavedSnapshot = null; +let _lsEditorSource = ""; // lyrics_source of whatever was loaded +let _lsEditorStems = []; // [{id, file, url}] +let _lsEditorDuration = 0; // best-known song duration (manifest, then