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) + ? `` + : ''; document.getElementById('ls-progress').innerHTML = `

Alignment failed

${esc(data.error)}

+ ${details}
`; return; } diff --git a/tests/test_helpers.py b/tests/test_helpers.py index a9c9bff..3b5c4fe 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -27,6 +27,8 @@ def test_word_alignment_rejects_duet_like_within_line_gap(): ] errors = routes._alignment_plausibility_errors(segments, "word") assert errors and "within lyric line" in errors[0] + # The segment number is what the 422 surfaces to the user, so pin it. + assert "before segment 3" in errors[0] def test_word_alignment_allows_gap_at_a_line_boundary(): @@ -38,6 +40,43 @@ def test_word_alignment_allows_gap_at_a_line_boundary(): assert routes._alignment_plausibility_errors(segments, "word") == [] +def test_word_alignment_allows_a_gap_under_the_line_threshold(): + """The within-line rule is a wide tolerance, not a no-gap requirement.""" + segments = [ + {"text": "How", "start": 0.031, "new_line": True}, + {"text": "can", "start": 7.5}, + ] + assert routes._alignment_plausibility_errors(segments, "word") == [] + + +def test_alignment_rejects_unusable_segment_end_times(): + """`/save` writes `d = end - start` unfiltered, so a bad end lands in lyrics.json.""" + cases = [ + ({"text": "you", "start": 1.0, "end": "soon"}, "no numeric end time"), + ({"text": "you", "start": 1.0, "end": float("nan")}, "non-finite end time"), + ({"text": "you", "start": 14.49, "end": 14.2}, "ends before it starts"), + ] + for segment, expected in cases: + errors = routes._alignment_plausibility_errors([segment], "word") + assert len(errors) == 1 and expected in errors[0], segment + + +def test_line_granularity_skips_the_within_line_gap_but_not_chronology(): + """`line` responses carry no `new_line`, so only the gap rule is skipped.""" + spaced = [ + {"text": "first line", "start": 0.0, "end": 3.0}, + {"text": "second line", "start": 20.0, "end": 24.0}, + ] + assert routes._alignment_plausibility_errors(spaced, "line") == [] + out_of_order = [ + {"text": "first line", "start": 20.0, "end": 24.0}, + {"text": "second line", "start": 0.0, "end": 3.0}, + ] + assert routes._alignment_plausibility_errors(out_of_order, "line") == [ + "alignment timestamps are not monotonic" + ] + + # ── path containment ─────────────────────────────────────────────────────── def test_safe_dlc_path_rejects_traversal_and_absolute(tmp_path): From 755113719c81fcea73dcc33e00f664044eb48d42 Mon Sep 17 00:00:00 2001 From: Carolina <79524656+carochacs@users.noreply.github.com> Date: Mon, 28 Sep 2026 22:17:05 -0600 Subject: [PATCH 4/4] refactor: split _alignment_plausibility_errors to reduce complexity CodeFactor flagged this function as a Complex Method (routes.py#L283-330). Extract span parsing (_parse_segment_span) and the within-line gap check (_within_line_gap_error) into their own helpers so the main function reads as a sequence of checks. Pure refactor - same error strings, same behavior, verified against the existing test_helpers.py cases. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01U2BDXmZrLF1kq7RE823NHw --- routes.py | 79 ++++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 55 insertions(+), 24 deletions(-) diff --git a/routes.py b/routes.py index f543d23..7e6ce8d 100644 --- a/routes.py +++ b/routes.py @@ -280,6 +280,50 @@ def _format_lrc_word_level(segments: list[dict]) -> str: MAX_GAP_WITHIN_LINE_SECONDS = 8.0 +def _parse_segment_span(segment: dict, index: int) -> tuple[float, float | None] | str: + """Parse and validate one segment's `start`/`end`. + + Returns `(start, end)` (`end` is `None` when the segment carries none) + on success, or a single error string on failure. Split out of + `_alignment_plausibility_errors` so that function reads as a sequence of + checks rather than one large branchy body. + """ + 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 "end" not in segment: + return start, None + + 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" + return start, end + + +def _within_line_gap_error( + start: float, previous_in_line: float | None, index: int, +) -> str | None: + """Return an error string when `start` opens too wide a gap since the + previous segment of the same lyric line, else `None`.""" + if previous_in_line is None: + return None + gap = start - previous_in_line + if gap <= MAX_GAP_WITHIN_LINE_SECONDS: + return None + return f"implausible {gap:.1f}s gap within lyric line before segment {index + 1}" + + 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: @@ -296,35 +340,22 @@ def _alignment_plausibility_errors(segments: object, granularity: str) -> list[s 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"] + + parsed = _parse_segment_span(segment, index) + if isinstance(parsed, str): + return [parsed] + start, _end = parsed + if previous_start is not None and start < previous_start: return ["alignment timestamps are not monotonic"] - 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}" - ) + gap_error = _within_line_gap_error(start, previous_in_line, index) + if gap_error: + errors.append(gap_error) + previous_start = start previous_in_line = start return errors