Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion plugin.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"id": "lyrics_sync",
"name": "Lyrics Sync",
"version": "1.1.1",
"version": "1.1.3",
"private": false,
"nav": {
"label": "Lyrics Sync",
Expand Down
124 changes: 101 additions & 23 deletions routes.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
"""Lyrics Sync plugin — author, time-align, and hand-edit synced lyrics."""

import json
import math
import os
import re
import shutil
import zipfile
from pathlib import Path, PurePosixPath, PureWindowsPath
Expand Down Expand Up @@ -163,35 +165,88 @@ def _find_vocals_stem(filename: str) -> Path | None:
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.
"""
total_centis = round(max(0.0, float(t)) * 100)
Comment thread
cchacs marked this conversation as resolved.
Resolved
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
lines.append(f"[{_lrc_timestamp(t)}]{seg.get('text', '')}")
return "\n".join(lines) + "\n"


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"]:
Comment thread
cchacs marked this conversation as resolved.
Resolved
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
word_parts.append(f"<{_lrc_timestamp(wt)}>{w.get('text', '')}")
text = " ".join(word_parts)
lines.append(f"[{minutes:02d}:{seconds:05.2f}]{text}")
lines.append(f"[{_lrc_timestamp(t)}]{text}")
return "\n".join(lines) + "\n"


Expand Down Expand Up @@ -381,11 +436,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 = []
Expand All @@ -406,7 +461,11 @@ def ls_export(data: dict):
# 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('"', '\\"')
# _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(
Expand Down Expand Up @@ -436,6 +495,27 @@ def ls_save(data: dict):

if not filename or not segments:
return JSONResponse({"error": "filename and segments required"}, 400)
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:
Expand Down Expand Up @@ -468,8 +548,8 @@ def ls_save(data: dict):
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),
"t": round(float(seg["start"]), 3),
"d": round(float(seg["end"]) - float(seg["start"]), 3),
"w": text,
})

Expand Down Expand Up @@ -576,8 +656,6 @@ def ls_save_lyrics(data: dict):
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):
Expand Down
91 changes: 91 additions & 0 deletions tests/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,19 @@ def test_format_lrc_empty_segments_yields_trailing_newline_only():
assert routes._format_lrc([]) == "\n"


def test_ascii_safe_filename_component_folds_non_latin1_chars():
# Starlette encodes header values as Latin-1; anything above U+00FF must
# be folded before it reaches a raw `filename=` fallback or the response
# raises UnicodeEncodeError at send time.
folded = routes._ascii_safe_filename_component("\u7c73\u6d25\u7384\u5e2b - Lemon")
assert folded == "____ - Lemon"
folded.encode("latin-1") # must not raise


def test_ascii_safe_filename_component_leaves_ascii_untouched():
assert routes._ascii_safe_filename_component("My Song - Artist") == "My Song - Artist"


def test_format_lrc_word_level_inlines_word_timestamps():
segments = [
{"start": 0.0, "text": "Hello World", "words": [
Expand All @@ -221,3 +234,81 @@ def test_format_lrc_word_level_inlines_word_timestamps():
]
lrc = routes._format_lrc_word_level(segments)
assert lrc == "[00:00.00]<00:00.00>Hello <00:00.50>World\n"


def test_lrc_timestamp_rolls_seconds_into_next_minute_on_rounding():
# int(t // 60) + f"{t % 60:05.2f}" independently truncates the minute and
# rounds the seconds, so a value like 119.999 used to print the invalid
# "01:60.00" instead of rolling over to "02:00.00". Round to whole
# centiseconds first, then split, so the carry happens before formatting.
assert routes._lrc_timestamp(119.999) == "02:00.00"
assert routes._lrc_timestamp(59.996) == "01:00.00"
assert routes._lrc_timestamp(65.0) == "01:05.00"
assert routes._lrc_timestamp(0.0) == "00:00.00"


def test_format_lrc_skips_malformed_segments_instead_of_raising():
segments = [
{"start": 1.0, "text": "kept"},
{"text": "missing start"},
"not a dict",
{"start": "not a number", "text": "bad start"},
None,
]
assert routes._format_lrc(segments) == "[00:01.00]kept\n"


def test_format_lrc_missing_text_defaults_to_empty_string():
assert routes._format_lrc([{"start": 1.0}]) == "[00:01.00]\n"


def test_format_lrc_word_level_skips_malformed_words():
segments = [
{"start": 0.0, "text": "Hello World", "words": [
{"start": 0.0, "text": "Hello"},
{"text": "no start, dropped"},
"not a dict",
{"start": 0.5, "text": "World"},
]},
]
lrc = routes._format_lrc_word_level(segments)
assert lrc == "[00:00.00]<00:00.00>Hello <00:00.50>World\n"


def test_format_lrc_word_level_tolerates_null_words_field():
# "words": null iterated directly (`for w in seg["words"]`) raises
# TypeError outside any try/except -- a 500 on otherwise well-formed
# input. `isinstance(seg.get("words"), list)` must reject None the
# same way it rejects any other non-list shape.
segments = [{"start": 0.0, "text": "Hello", "words": None}]
assert routes._format_lrc_word_level(segments) == "[00:00.00]Hello\n"


def test_format_lrc_skips_non_finite_start_instead_of_raising():
# float("inf")/float("nan") parse without raising, so the existing
# KeyError/TypeError/ValueError guard doesn't catch them -- they used
# to reach _lrc_timestamp's `round(inf * 100)`, which raises
# OverflowError ("cannot convert float infinity to integer") and 500s
# the export. Same for the numeric-literal overflow case (1e999 is inf).
segments = [
{"start": 1.0, "text": "kept"},
{"start": float("inf"), "text": "inf dropped"},
{"start": float("-inf"), "text": "-inf dropped"},
{"start": float("nan"), "text": "nan dropped"},
{"start": 1e999, "text": "overflow-literal dropped"},
]
assert routes._format_lrc(segments) == "[00:01.00]kept\n"


def test_format_lrc_word_level_skips_non_finite_start_and_word_start():
segments = [
{"start": float("inf"), "text": "seg dropped", "words": [
{"start": 0.0, "text": "irrelevant"},
]},
{"start": 0.0, "text": "kept", "words": [
{"start": float("nan"), "text": "word dropped"},
{"start": 0.5, "text": "kept-word"},
]},
]
lrc = routes._format_lrc_word_level(segments)
assert lrc == "[00:00.00]<00:00.50>kept-word\n"
Loading