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. 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" 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 9e558f4..d77b2a0 100644 --- a/plugin.json +++ b/plugin.json @@ -1,11 +1,11 @@ { "id": "lyrics_sync", "name": "Lyrics Sync", - "version": "1.0.0", + "version": "1.1.4", "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 f27a3c4..ae56108 100644 --- a/routes.py +++ b/routes.py @@ -1,9 +1,15 @@ -"""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 math import os -from pathlib import Path +import re +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 @@ -13,6 +19,118 @@ 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`/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 + 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 _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" @@ -29,39 +147,89 @@ 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 = dlc / filename - 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 +def _ascii_safe_filename_component(name: str) -> str: + """Fold `name` to printable ASCII for use in the legacy `filename=` + Content-Disposition fallback. + + Starlette/Werkzeug-style header encoding treats header VALUES as + Latin-1 (RFC 7230), so any character above U+00FF (CJK, Cyrillic, + emoji, ...) raises UnicodeEncodeError at response-send time if it + reaches that header raw — turning a perfectly ordinary title/artist + into a 500. The `filename*=` RFC 5987 form (built separately, from the + unfolded name) still carries the real UTF-8 name via percent-encoding + regardless, so this fallback only needs to be non-crashing, not exact. + """ + return re.sub(r"[^\x20-\x7e]", "_", name) + + +def _lrc_timestamp(t: float) -> str: + """Format a time in seconds as an LRC "mm:ss.xx" timestamp. + + Computing minutes/seconds separately with `int(t // 60)` / + `f"{t % 60:05.2f}"` looks right but isn't: `:05.2f` rounds its operand, + so a seconds remainder like 59.996 prints as "60.00" instead of rolling + into the next minute — e.g. t=119.999 produced the invalid + "[01:60.00]" rather than "[02:00.00]". Round to whole centiseconds + FIRST, then split into minutes/seconds, so the rollover happens before + formatting rather than during it. + """ + seconds = float(t) + # Callers gate on math.isfinite(t) before calling, but that alone + # isn't enough: a value can be finite and still overflow once scaled + # to centiseconds (e.g. 1e307 * 100 = 1e309 exceeds the max + # representable double and becomes inf), which round() below would + # turn into an unhelpful OverflowError instead of the clean skip the + # finiteness check was meant to guarantee. + scaled = max(0.0, seconds) * 100 + if not math.isfinite(scaled): + raise ValueError("LRC timestamp must be finite") + total_centis = round(scaled) + minutes, centis = divmod(total_centis, 6000) + return f"{minutes:02d}:{centis / 100:05.2f}" + + def _format_lrc(segments: list[dict]) -> str: - """Convert alignment segments to standard LRC format.""" + """Convert alignment segments to standard LRC format. + + Segments come from the alignment server's JSON response (or, for + /export, straight from the request body) — parseable JSON, but not + guaranteed to carry the keys this needs. A malformed segment (missing + `start`, a non-numeric `start`) is skipped rather than raising + KeyError/TypeError and 500ing the whole export. + """ lines = [] for seg in segments: - t = seg["start"] - minutes = int(t // 60) - seconds = t % 60 - lines.append(f"[{minutes:02d}:{seconds:05.2f}]{seg['text']}") + if not isinstance(seg, dict): + continue + try: + t = float(seg["start"]) + except (KeyError, TypeError, ValueError): + continue + if not math.isfinite(t): + continue + try: + timestamp = _lrc_timestamp(t) + except ValueError: + continue + lines.append(f"[{timestamp}]{seg.get('text', '')}") return "\n".join(lines) + "\n" @@ -69,23 +237,101 @@ def _format_lrc_word_level(segments: list[dict]) -> str: """Convert word-level alignment segments to enhanced LRC format.""" lines = [] for seg in segments: - t = seg["start"] - minutes = int(t // 60) - seconds = t % 60 - text = seg["text"] + if not isinstance(seg, dict): + continue + try: + t = float(seg["start"]) + except (KeyError, TypeError, ValueError): + continue + if not math.isfinite(t): + continue + text = seg.get("text", "") # Word-level: include inline timestamps for each word - if "words" in seg: + if isinstance(seg.get("words"), list): word_parts = [] for w in seg["words"]: - wt = w["start"] - wm = int(wt // 60) - ws = wt % 60 - word_parts.append(f"<{wm:02d}:{ws:05.2f}>{w['text']}") + if not isinstance(w, dict): + continue + try: + wt = float(w["start"]) + except (KeyError, TypeError, ValueError): + continue + if not math.isfinite(wt): + continue + try: + word_timestamp = _lrc_timestamp(wt) + except ValueError: + continue + word_parts.append(f"<{word_timestamp}>{w.get('text', '')}") text = " ".join(word_parts) - lines.append(f"[{minutes:02d}:{seconds:05.2f}]{text}") + try: + timestamp = _lrc_timestamp(t) + except ValueError: + continue + lines.append(f"[{timestamp}]{text}") 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 @@ -96,16 +342,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)} @@ -160,7 +431,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']}"}, @@ -181,11 +458,11 @@ def ls_export(data: dict): Returns: LRC file download. """ segments = data.get("segments", []) - if not segments: + if not isinstance(segments, list) or not segments: return JSONResponse({"error": "No segments provided"}, 400) - title = data.get("title", "") - artist = data.get("artist", "") + title = data.get("title", "") if isinstance(data.get("title", ""), str) else "" + artist = data.get("artist", "") if isinstance(data.get("artist", ""), str) else "" # Build LRC header + body header_lines = [] @@ -201,71 +478,234 @@ 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_safe_filename_component folds anything outside printable + # ASCII to `_` in the legacy fallback only; `filename*=` below still + # carries the real UTF-8 name via percent-encoding regardless. + ascii_safe_name = _ascii_safe_filename_component(safe_name) + ascii_name = ascii_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}" + ), }, ) @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": [...]} - Writes a lyrics JSON file and updates the sloppak manifest. + Expects: {"filename": str, "segments": [...], "granularity": str?} + 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") 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 = dlc / filename - 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) + if not isinstance(segments, list): + return JSONResponse({"error": "segments must be a list"}, 400) + + # Validate up front: the loop below indexes seg["text"]/["start"]/["end"] + # and peeks segments[i + 1] for the granularity-aware line-break logic, + # so a malformed segment (missing key, non-numeric start/end, a + # non-dict entry — e.g. a truncated /align response, or a hand-crafted + # request) would otherwise raise KeyError/TypeError/AttributeError and + # 500 the whole save instead of reporting a clear 400. + for i, seg in enumerate(segments): + if not isinstance(seg, dict): + return JSONResponse({"error": f"segment {i} is not an object"}, 400) + if not isinstance(seg.get("text"), str): + return JSONResponse({"error": f"segment {i} is missing a string 'text'"}, 400) + try: + seg_start = float(seg["start"]) + seg_end = float(seg["end"]) + except (KeyError, TypeError, ValueError): + return JSONResponse({"error": f"segment {i} has a non-numeric start/end"}, 400) + if not (math.isfinite(seg_start) and math.isfinite(seg_end)): + return JSONResponse({"error": f"segment {i} has a non-finite start/end"}, 400) + + 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}, ...] - # 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"], + "t": round(float(seg["start"]), 3), + "d": round(float(seg["end"]) - float(seg["start"]), 3), + "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} + + @app.get("/api/plugins/lyrics_sync/lyrics") + def ls_get_lyrics(filename: str = ""): + """Load a sloppak's existing lyrics + audio info for the editor. - # Update manifest to reference the lyrics file - manifest_path = source_dir / "manifest.yaml" - if manifest_path.exists(): + 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) + + 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..ebed1ec 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,129 @@

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 6003eed..1a74075 100644 --- a/screen.js +++ b/screen.js @@ -51,20 +51,56 @@ async function lsSearchSongs() { return; } - container.innerHTML = withStems.map(s => ` -
-
- ${esc(s.title)} - ${esc(s.artist)} -
- ${s.stem_count} stems -
- `).join(''); -} - -function lsSelectSong(encodedFilename, title, artist) { - _lsSelectedFilename = decodeURIComponent(encodedFilename); + // 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(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; @@ -73,15 +109,25 @@ function lsSelectSong(encodedFilename, 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 ───────────────────────────────────────────────────────── @@ -179,21 +225,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 +310,7 @@ async function lsSave() { body: JSON.stringify({ filename: _lsSelectedFilename, segments: _lsAlignmentResult, + granularity: _lsGetGranularity(), }), }); @@ -267,6 +330,1046 @@ 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