From 721b3400b43e3698a9a866b119f1a72913380e4e Mon Sep 17 00:00:00 2001 From: Carolina <79524656+carochacs@users.noreply.github.com> Date: Mon, 28 Sep 2026 17:26:32 -0600 Subject: [PATCH 1/4] fix: reject unsafe duet alignment previews --- routes.py | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/routes.py b/routes.py index ae56108..4e8e988 100644 --- a/routes.py +++ b/routes.py @@ -272,6 +272,38 @@ def _format_lrc_word_level(segments: list[dict]) -> str: return "\n".join(lines) + "\n" +def _alignment_plausibility_errors(segments: object, granularity: str) -> list[str]: + """Return safety errors for an alignment preview before it can be saved.""" + if not isinstance(segments, list) or not segments: + return ["alignment returned no segments"] + if granularity not in {"word", "syllable"}: + return [] + previous_start = None + previous_in_line = None + errors = [] + for index, segment in enumerate(segments): + if not isinstance(segment, dict): + return [f"alignment segment {index} is not an object"] + try: + start = float(segment["start"]) + except (KeyError, TypeError, ValueError): + return [f"alignment segment {index} has no numeric start time"] + if not math.isfinite(start): + return [f"alignment segment {index} has a non-finite start time"] + if previous_start is not None and start < previous_start: + return ["alignment timestamps are not monotonic"] + if segment.get("new_line"): + previous_in_line = None + if previous_in_line is not None and start - previous_in_line > 8.0: + errors.append( + f"implausible {start - previous_in_line:.1f}s gap within lyric line " + f"before segment {index + 1}" + ) + previous_start = start + previous_in_line = start + return errors + + # ── Persistence: write lyrics.json + patch manifest + re-zip ────────────────── def _atomic_write_json(path: Path, payload) -> None: @@ -444,6 +476,21 @@ def ls_align(data: dict): 502, ) + plausibility_errors = _alignment_plausibility_errors( + result.get("segments"), granularity, + ) + if plausibility_errors: + # /align is read-only: rejecting this preview leaves any + # existing lyrics unchanged instead of offering bad data to + # the separate save route. + return JSONResponse( + { + "error": "Alignment preview is unsafe to save", + "details": plausibility_errors, + }, + 422, + ) + return result except requests.Timeout: return JSONResponse({"error": "Alignment request timed out"}, 504) From 7827628f22b05ba1d54e0b0dc11f527a7e854a06 Mon Sep 17 00:00:00 2001 From: Carolina <79524656+carochacs@users.noreply.github.com> Date: Mon, 28 Sep 2026 17:26:34 -0600 Subject: [PATCH 2/4] test: cover duet alignment timing safety --- tests/test_helpers.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/tests/test_helpers.py b/tests/test_helpers.py index df45db3..a9c9bff 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -18,6 +18,26 @@ import routes # noqa: E402 +def test_word_alignment_rejects_duet_like_within_line_gap(): + """Ordered duet words can still be unsafe within a caller lyric line.""" + segments = [ + {"text": "How", "start": 0.031, "new_line": True}, + {"text": "can", "start": 0.11}, + {"text": "you", "start": 14.49}, + ] + errors = routes._alignment_plausibility_errors(segments, "word") + assert errors and "within lyric line" in errors[0] + + +def test_word_alignment_allows_gap_at_a_line_boundary(): + segments = [ + {"text": "first", "start": 0.0, "new_line": True}, + {"text": "line", "start": 0.4}, + {"text": "next", "start": 20.0, "new_line": True}, + ] + assert routes._alignment_plausibility_errors(segments, "word") == [] + + # ── path containment ─────────────────────────────────────────────────────── def test_safe_dlc_path_rejects_traversal_and_absolute(tmp_path): From 548492672e60c555cdb628ee351289ab5beee7c7 Mon Sep 17 00:00:00 2001 From: "pullfrog[bot]" <226033991+pullfrog[bot]@users.noreply.github.com> Date: Tue, 29 Sep 2026 01:30:49 +0000 Subject: [PATCH 3/4] fix: surface alignment rejection details and guard segment spans MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up to the plausibility guard: the 422 already carried a `details` list that the UI dropped, and the per-segment checks skipped `end` and skipped `line` granularity entirely. - render `data.details` (escaped) in the align error panel so a rejected preview names the offending segments - reject non-numeric, non-finite, or reversed `end` values — /save writes `d = end - start` with no `d <= 0` filter - keep the within-line gap rule word/syllable-only (it needs the server's `new_line` markers) but apply the per-segment and monotonicity checks at every granularity - extract MAX_GAP_WITHIN_LINE_SECONDS and document the assumption - cover sub-threshold gaps, unusable end times, and the line-granularity split with tests --- routes.py | 44 ++++++++++++++++++++++++++++++++++--------- screen.js | 9 +++++++++ tests/test_helpers.py | 39 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 83 insertions(+), 9 deletions(-) diff --git a/routes.py b/routes.py index 4e8e988..f543d23 100644 --- a/routes.py +++ b/routes.py @@ -272,12 +272,24 @@ def _format_lrc_word_level(segments: list[dict]) -> str: return "\n".join(lines) + "\n" +# Widest gap tolerated between two segments of the same lyric line. A duet +# hands off to the second singer partway through a line, so anything wider is +# far likelier to be a word aligned into the wrong place than a deliberate +# pause — pauses *between* lines are unconstrained, because the server marks +# those with `new_line` rather than with timing. +MAX_GAP_WITHIN_LINE_SECONDS = 8.0 + + def _alignment_plausibility_errors(segments: object, granularity: str) -> list[str]: """Return safety errors for an alignment preview before it can be saved.""" if not isinstance(segments, list) or not segments: return ["alignment returned no segments"] - if granularity not in {"word", "syllable"}: - return [] + # The within-line gap rule needs the server's `new_line` markers, which + # only word/syllable responses carry — at `line` granularity every + # segment is already a whole line. The per-segment checks below hold at + # every granularity: a reversed or non-finite span is just as unsavable + # whichever way the caller asked for it. + check_gaps = granularity in {"word", "syllable"} previous_start = None previous_in_line = None errors = [] @@ -292,13 +304,27 @@ def _alignment_plausibility_errors(segments: object, granularity: str) -> list[s return [f"alignment segment {index} has a non-finite start time"] if previous_start is not None and start < previous_start: return ["alignment timestamps are not monotonic"] - if segment.get("new_line"): - previous_in_line = None - if previous_in_line is not None and start - previous_in_line > 8.0: - errors.append( - f"implausible {start - previous_in_line:.1f}s gap within lyric line " - f"before segment {index + 1}" - ) + if "end" in segment: + try: + end = float(segment["end"]) + except (TypeError, ValueError): + return [f"alignment segment {index} has no numeric end time"] + if not math.isfinite(end): + return [f"alignment segment {index} has a non-finite end time"] + # `/save` writes `d = end - start` with no `d <= 0` filter (unlike + # `/save-lyrics`), so a reversed span would land in lyrics.json. + if end < start: + return [f"alignment segment {index} ends before it starts"] + if check_gaps: + if segment.get("new_line"): + previous_in_line = None + if previous_in_line is not None: + gap = start - previous_in_line + if gap > MAX_GAP_WITHIN_LINE_SECONDS: + errors.append( + f"implausible {gap:.1f}s gap within lyric line " + f"before segment {index + 1}" + ) previous_start = start previous_in_line = start return errors diff --git a/screen.js b/screen.js index a5e4783..f4df80b 100644 --- a/screen.js +++ b/screen.js @@ -198,10 +198,19 @@ async function lsAlign() { const data = await resp.json(); if (data.error) { + // A plausibility rejection (422) names the offending segments in + // `details`; without them the user only sees "unsafe to save" + // and has to guess whether to retry, re-align, or change + // granularity. + const details = (Array.isArray(data.details) && data.details.length) + ? `
Alignment failed
${esc(data.error)}
+ ${details}