diff --git a/routes.py b/routes.py index ae56108..7e6ce8d 100644 --- a/routes.py +++ b/routes.py @@ -272,6 +272,95 @@ 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 _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: + return ["alignment returned no segments"] + # 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 = [] + for index, segment in enumerate(segments): + if not isinstance(segment, dict): + return [f"alignment segment {index} is not an object"] + + 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 check_gaps: + if segment.get("new_line"): + previous_in_line = None + 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 + + # ── Persistence: write lyrics.json + patch manifest + re-zip ────────────────── def _atomic_write_json(path: Path, payload) -> None: @@ -444,6 +533,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) 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}