From c6edbe465dc7d4ecbfea275b72cdb859a997905a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 13 Aug 2026 03:14:24 +0000 Subject: [PATCH 1/4] 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. --- README.md | 47 ++- plugin.json | 4 +- routes.py | 349 ++++++++++++++++---- screen.html | 115 ++++++- screen.js | 933 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 1378 insertions(+), 70 deletions(-) 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 9690b00..d7cdfb0 100644 --- a/plugin.json +++ b/plugin.json @@ -1,11 +1,11 @@ { "id": "lyrics_sync", "name": "Lyrics Sync", - "version": "1.0.1", + "version": "1.1.0", "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 19e42b4..9cefc72 100644 --- a/routes.py +++ b/routes.py @@ -1,9 +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 @@ -19,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 @@ -45,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" @@ -61,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 @@ -120,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 @@ -270,13 +405,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") @@ -284,17 +420,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}, ...] @@ -327,27 +456,137 @@ 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 the same way the sloppak loader itself + filters lyrics.json on read (lib/sloppak.py) so a save can't + write something the loader would silently drop on the next load: + every entry must have a string `w` and finite numeric `t`/`d`; + entries with `d <= 0` are dropped; the rest are rounded and + sorted by `t`. + + 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..a9dfc80 100644 --- a/screen.js +++ b/screen.js @@ -86,6 +86,11 @@ 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. + if (typeof lsCloseEditor === 'function') lsCloseEditor(); + _lsSelectedFilename = filename; _lsSelectedTitle = title; _lsSelectedArtist = artist; @@ -95,15 +100,19 @@ 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(); + _lsSelectedFilename = null; _lsSelectedTitle = ""; _lsSelectedArtist = ""; document.getElementById('ls-selected-song').classList.add('hidden'); document.getElementById('ls-selected-label').textContent = ''; _lsUpdateAlignBtn(); + if (typeof _lsUpdateOpenEditorBtn === 'function') _lsUpdateOpenEditorBtn(); } // ── Lyrics input ───────────────────────────────────────────────────────── @@ -306,6 +315,891 @@ 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; +let _lsEditorSource = ""; // lyrics_source of whatever was loaded +let _lsEditorStems = []; // [{id, file, url}] +let _lsEditorDuration = 0; // best-known song duration (manifest, then