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
104 changes: 104 additions & 0 deletions routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Comment thread
pullfrog[bot] marked this conversation as resolved.
Resolved
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:
Expand Down Expand Up @@ -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)
Expand Down
9 changes: 9 additions & 0 deletions screen.js
Original file line number Diff line number Diff line change
Expand Up @@ -198,10 +198,19 @@
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)
? `<ul class="mt-2 space-y-1 text-gray-500">${data.details
.map(d => `<li>${esc(d)}</li>`).join('')}</ul>`

Check warning on line 207 in screen.js

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

screen.js#L207

'esc' is not defined.
: '';
document.getElementById('ls-progress').innerHTML = `
<div class="bg-red-900/20 border border-red-800/30 rounded-xl p-4 text-sm">
<p class="text-red-400 font-semibold mb-1">Alignment failed</p>
<p class="text-gray-400">${esc(data.error)}</p>
${details}
</div>`;
return;
}
Expand Down Expand Up @@ -837,56 +846,56 @@

// ── rAF draw loop — cached refs only, no DOM queries ────────────────────

function _lsEditorDrawFrame() {
const canvas = _lsEditorEls.canvas;
if (!canvas || !_lsEditorOffscreen) return;
const ctx = canvas.getContext('2d');
ctx.drawImage(_lsEditorOffscreen, 0, 0);

const height = canvas.height;
const pxPerSec = _lsEditorPxPerSec;
const wrap = _lsEditorEls.timelineWrap;
// Cull blocks outside the scrolled viewport (+padding) so a long song
// at a wide zoom doesn't pay for thousands of off-screen fillRect calls
// every frame.
const scrollLeft = wrap ? wrap.scrollLeft : 0;
const viewW = wrap ? wrap.clientWidth : canvas.width;
const visStart = Math.max(0, scrollLeft - 150);
const visEnd = scrollLeft + viewW + 150;

for (let i = 0; i < _lsEditorSyllables.length; i++) {
const syl = _lsEditorSyllables[i];
if (syl.t == null || syl.d == null) continue;
const x = syl.t * pxPerSec;
const w = Math.max(2, syl.d * pxPerSec);
if (x + w < visStart || x > visEnd) continue;

const selected = i === _lsEditorSelectedIndex;
ctx.fillStyle = selected ? 'rgba(232,192,64,0.55)' : 'rgba(64,128,224,0.35)';
ctx.strokeStyle = selected ? '#e8c040' : 'rgba(64,128,224,0.85)';
ctx.lineWidth = selected ? 2 : 1;
ctx.fillRect(x, 8, w, height - 16);
ctx.strokeRect(x, 8, w, height - 16);
if (w > 14) {
ctx.save();
ctx.beginPath();
ctx.rect(x, 0, w, height);
ctx.clip();
ctx.fillStyle = '#e5e7eb';
ctx.font = '11px monospace';
ctx.textBaseline = 'middle';
const label = syl.w + (syl.join ? '-' : syl.brk ? '+' : '');
ctx.fillText(label, x + 3, height / 2);
ctx.restore();
}
}

if (_lsEditorLoopA != null) _lsEditorDrawMarker(ctx, _lsEditorLoopA * pxPerSec, height, '#34d399');
if (_lsEditorLoopB != null) _lsEditorDrawMarker(ctx, _lsEditorLoopB * pxPerSec, height, '#34d399');

const audio = _lsEditorEls.audio;
if (audio) _lsEditorDrawMarker(ctx, (audio.currentTime || 0) * pxPerSec, height, '#ffffff');
}

Check notice on line 898 in screen.js

View check run for this annotation

codefactor.io / CodeFactor

screen.js#L849-L898

Complex Method

function _lsEditorDrawMarker(ctx, x, height, color) {
ctx.strokeStyle = color;
Expand Down
59 changes: 59 additions & 0 deletions tests/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,65 @@
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]
# 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():
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") == []


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):
Expand Down
Loading