Commit ae06a8fd authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Real line-synced lyrics: stop discarding LRC timing, store it

fetch_lyrics() now tries syncedlyrics with synced_only=True first (a real
line-by-line-timed hit, not a fuzzy fallback) and only drops to plain-text
search if nothing timed exists anywhere. Previously it always stripped
timestamps immediately, throwing away data the frontend now needs for a
real Spotify-style highlighted lyrics view.

New synced_lyrics column (LibrarySong + IdentifiedTrack cache), JSON-encoded
[[seconds, text], ...], threaded through the shared _identify_tag_and_store
pipeline (upload, tag, and the Telegram bulk-scan job all go through it) and
exposed via GET /library/lyrics/{file_id}.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 4d1f15ee
Pipeline #1144 passed with stage
in 6 minutes and 41 seconds
"""add synced_lyrics to library_songs and identified_tracks
Revision ID: 4551428f6b16
Revises: 9f59c50ce5ca
Create Date: 2026-08-31 10:40:06.456335
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '4551428f6b16'
down_revision: Union[str, Sequence[str], None] = '9f59c50ce5ca'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
op.add_column('identified_tracks', sa.Column('synced_lyrics', sa.String(), nullable=True))
op.add_column('library_songs', sa.Column('synced_lyrics', sa.String(), nullable=True))
def downgrade() -> None:
"""Downgrade schema."""
op.drop_column('library_songs', 'synced_lyrics')
op.drop_column('identified_tracks', 'synced_lyrics')
import json
import os
from fastapi import APIRouter, Depends, HTTPException, Form
from fastapi.responses import FileResponse
......@@ -43,7 +44,11 @@ async def get_lyrics(file_id: int, db: Session = Depends(get_db), current_user:
song = db.query(LibrarySong).filter(LibrarySong.id == file_id, LibrarySong.user_id == current_user.id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
return {"status": "success", "lyrics": song.lyrics}
return {
"status": "success",
"lyrics": song.lyrics,
"synced_lyrics": json.loads(song.synced_lyrics) if song.synced_lyrics else None,
}
@router.post("/library/search")
async def search_library(query: str = Form(...), db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
......
import asyncio
import json
import shutil
import urllib.parse
from typing import List
......@@ -92,6 +93,7 @@ async def _identify_tag_and_store(
"year": "",
"has_lyrics": bool(existing_song.lyrics),
"lyrics": existing_song.lyrics,
"synced_lyrics": json.loads(existing_song.synced_lyrics) if existing_song.synced_lyrics else None,
"cover_art": existing_song.coverart,
},
}
......@@ -106,6 +108,7 @@ async def _identify_tag_and_store(
'title': cached.title, 'artist': cached.artist, 'album': cached.album,
'year': cached.year, 'genre': cached.genre, 'track_number': cached.track_number,
'source': cached.source, 'coverart': cached.coverart, 'lyrics': cached.lyrics,
'synced_lyrics': json.loads(cached.synced_lyrics) if cached.synced_lyrics else None,
}
else:
candidates = await identify_audio(raw_file_path)
......@@ -116,8 +119,9 @@ async def _identify_tag_and_store(
candidate = gemini_result if gemini_result else {}
if not candidate.get("lyrics"):
lyrics = await fetch_lyrics(candidate.get("title", ""), candidate.get("artist", ""))
candidate["lyrics"] = lyrics
lyrics_result = await fetch_lyrics(candidate.get("title", ""), candidate.get("artist", ""))
candidate["lyrics"] = lyrics_result["lyrics"]
candidate["synced_lyrics"] = lyrics_result["synced_lyrics"]
if not candidate.get("genre") or candidate.get("genre") == "Unknown Genre":
title, artist = candidate.get("title", ""), candidate.get("artist", "")
......@@ -146,6 +150,7 @@ async def _identify_tag_and_store(
source=candidate.get('source', ''),
coverart=candidate.get('coverart', ''),
lyrics=candidate.get('lyrics', ''),
synced_lyrics=json.dumps(candidate['synced_lyrics']) if candidate.get('synced_lyrics') else None,
))
try:
db.commit()
......@@ -166,6 +171,7 @@ async def _identify_tag_and_store(
genre=candidate.get('genre', ''),
coverart=candidate.get('coverart', ''),
lyrics=candidate.get('lyrics', ''),
synced_lyrics=json.dumps(candidate['synced_lyrics']) if candidate.get('synced_lyrics') else None,
file_path=final_path,
fingerprint=fingerprint,
)
......@@ -188,6 +194,7 @@ async def _identify_tag_and_store(
"year": candidate.get('year', ''),
"has_lyrics": bool(library_song.lyrics),
"lyrics": library_song.lyrics,
"synced_lyrics": json.loads(library_song.synced_lyrics) if library_song.synced_lyrics else None,
"cover_art": library_song.coverart,
},
}
......
......@@ -99,6 +99,9 @@ class LibrarySong(Base):
genre = Column(String)
coverart = Column(String)
lyrics = Column(String)
# JSON-encoded [[seconds, text], ...], line-level LRC timing - null when no synced source
# was found (plain `lyrics` above still works as the static fallback either way).
synced_lyrics = Column(String, nullable=True)
file_path = Column(String)
# Same content fingerprint used to key IdentifiedTrack - lets us detect "this user already
# has this exact recording" before re-tagging and re-storing it, independent of title/
......@@ -268,6 +271,7 @@ class IdentifiedTrack(Base):
source = Column(String)
coverart = Column(String)
lyrics = Column(String)
synced_lyrics = Column(String, nullable=True) # same JSON-encoded [[seconds, text], ...] shape as LibrarySong
identified_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class Correction(Base):
......
......@@ -152,16 +152,65 @@ async def identify_with_gemini(file_path: str, lang_pref: str) -> dict:
logger.error(f"Gemini identification failed: {e}")
return None
async def fetch_lyrics(title: str, artist: str) -> str:
"""Fetches lyrics using syncedlyrics and strips timestamps."""
if title == 'Unknown Title': return None
_LRC_TIMESTAMP_RE = re.compile(r'\[(\d+):(\d+)(?:\.(\d+))?\]')
def parse_lrc(lrc_text: str) -> list[list] | None:
"""Parses real LRC line timestamps ([mm:ss.xx]text) into [[seconds, text], ...], sorted -
used for the line-by-line synced/highlighted lyrics view. Lines with no timestamp (LRC
metadata tags like [ar:...]/[ti:...], or a plain untimed line) are skipped rather than
guessed at - this is specifically for real sync data, not a best-effort approximation.
Returns None if nothing timed was found at all."""
lines: list[list] = []
for raw_line in lrc_text.splitlines():
raw_line = raw_line.strip()
if not raw_line:
continue
matches = list(_LRC_TIMESTAMP_RE.finditer(raw_line))
if not matches:
continue
text = _LRC_TIMESTAMP_RE.sub('', raw_line).strip()
if not text:
continue
for m in matches:
minutes, seconds, frac = m.groups()
total_seconds = int(minutes) * 60 + int(seconds) + (float(f"0.{frac}") if frac else 0.0)
lines.append([round(total_seconds, 2), text])
if not lines:
return None
lines.sort(key=lambda pair: pair[0])
return lines
async def fetch_lyrics(title: str, artist: str) -> dict:
"""Tries for real line-synced lyrics first (synced_only=True - returns nothing rather than
silently falling back to plain text, so a genuine miss doesn't masquerade as unsynced), then
falls back to whatever plain lyrics exist if no synced version is available anywhere.
Returns {"lyrics": str | None, "synced_lyrics": [[seconds, text], ...] | None} - lyrics is
derived from the parsed synced text when synced data was found, so the two never disagree."""
if title == 'Unknown Title':
return {"lyrics": None, "synced_lyrics": None}
search_term = f"{title} {artist}"
try:
lrc = await asyncio.to_thread(syncedlyrics.search, search_term, synced_only=True)
if lrc:
parsed = parse_lrc(lrc)
if parsed:
return {"lyrics": "\n".join(text for _, text in parsed), "synced_lyrics": parsed}
except Exception as e:
logger.error(f"Synced lyrics fetch error: {e}")
try:
lrc = await asyncio.to_thread(syncedlyrics.search, f"{title} {artist}")
lrc = await asyncio.to_thread(syncedlyrics.search, search_term)
if lrc:
clean_lines = [l.strip() for l in lrc.splitlines() if l.strip()]
clean_lines = [re.sub(r'\[\d+:\d+(:\d+)?(\.\d+)?\]', '', l) for l in clean_lines]
clean_lines = [re.sub(r'\[[a-zA-Z]+:.*?\]', '', l) for l in clean_lines]
return "\n".join([l for l in clean_lines if l])
plain = "\n".join([l for l in clean_lines if l])
if plain:
return {"lyrics": plain, "synced_lyrics": None}
except Exception as e:
logger.error(f"Lyrics fallback error: {e}")
return None
return {"lyrics": None, "synced_lyrics": None}
......@@ -195,7 +195,9 @@ async def process_and_send_audio(update: Update, context: ContextTypes.DEFAULT_T
log_correction(update.effective_user.id, candidate['title'], candidate['artist'], candidate['source'])
if not candidate.get('lyrics') and candidate['title'] != 'Unknown Title':
candidate['lyrics'] = await fetch_lyrics(candidate['title'], candidate['artist'])
# This flow tags-and-sends over Telegram directly, no LibrarySong row involved, so
# only the plain-text half is used here - nowhere to persist the synced timing.
candidate['lyrics'] = (await fetch_lyrics(candidate['title'], candidate['artist']))["lyrics"]
try:
final_path = await tag_and_convert_audio(raw_path, candidate)
......
......@@ -192,6 +192,29 @@ def test_library_lyrics_success(client, db_session, auth_as):
os.remove(path)
def test_library_lyrics_includes_synced_lyrics_when_present(client, db_session, auth_as):
headers, user = auth_as()
song, path = _make_library_song(
db_session, user.id, lyrics="la la la", synced_lyrics='[[0.0, "la"], [1.5, "la la"]]'
)
try:
response = client.get(f"/library/lyrics/{song.id}", headers=headers)
assert response.status_code == 200
assert response.json()["synced_lyrics"] == [[0.0, "la"], [1.5, "la la"]]
finally:
os.remove(path)
def test_library_lyrics_synced_lyrics_null_when_absent(client, db_session, auth_as):
headers, user = auth_as()
song, path = _make_library_song(db_session, user.id, lyrics="la la la")
try:
response = client.get(f"/library/lyrics/{song.id}", headers=headers)
assert response.json()["synced_lyrics"] is None
finally:
os.remove(path)
def test_library_lyrics_unknown_id(client, auth_as):
headers, _ = auth_as()
response = client.get("/library/lyrics/99999", headers=headers)
......
......@@ -98,6 +98,46 @@ def test_music_upload_success_creates_library_song(client, db_session, auth_as,
assert song.artist == "Test Artist"
def test_music_upload_persists_synced_lyrics(client, db_session, auth_as, mocker):
headers, user = auth_as()
candidate_without_lyrics = {**FAKE_CANDIDATE, "lyrics": None}
_mock_pipeline(mocker)
mocker.patch("src.api.routers.music.identify_audio", return_value=[candidate_without_lyrics])
mocker.patch(
"src.api.routers.music.fetch_lyrics",
return_value={"lyrics": "la\nla la", "synced_lyrics": [[0.0, "la"], [1.5, "la la"]]},
)
response = client.post(
"/music/upload",
headers=headers,
files={"file": ("test.mp3", b"fake mp3 bytes", "audio/mpeg")},
)
assert response.status_code == 200
assert response.json()["metadata"]["synced_lyrics"] == [[0.0, "la"], [1.5, "la la"]]
song = db_session.query(LibrarySong).filter(LibrarySong.user_id == user.id).first()
assert song.synced_lyrics == '[[0.0, "la"], [1.5, "la la"]]'
def test_music_upload_no_synced_lyrics_stays_null(client, db_session, auth_as, mocker):
headers, user = auth_as()
candidate_without_lyrics = {**FAKE_CANDIDATE, "lyrics": None}
_mock_pipeline(mocker)
mocker.patch("src.api.routers.music.identify_audio", return_value=[candidate_without_lyrics])
mocker.patch("src.api.routers.music.fetch_lyrics", return_value={"lyrics": None, "synced_lyrics": None})
response = client.post(
"/music/upload",
headers=headers,
files={"file": ("test.mp3", b"fake mp3 bytes", "audio/mpeg")},
)
assert response.json()["metadata"]["synced_lyrics"] is None
song = db_session.query(LibrarySong).filter(LibrarySong.user_id == user.id).first()
assert song.synced_lyrics is None
def test_music_upload_new_fingerprint_populates_cache(client, db_session, auth_as, mocker):
headers, _ = auth_as()
fingerprint = "fp-new-song-abc123"
......
import asyncio
from src.services.music_identification import fetch_lyrics, parse_lrc
def test_parse_lrc_basic_lines():
lrc = "[00:12.34]First line\n[00:15.00]Second line"
assert parse_lrc(lrc) == [[12.34, "First line"], [15.0, "Second line"]]
def test_parse_lrc_sorts_out_of_order_lines():
lrc = "[00:20.00]Later\n[00:05.00]Earlier"
assert parse_lrc(lrc) == [[5.0, "Earlier"], [20.0, "Later"]]
def test_parse_lrc_skips_metadata_tags():
lrc = "[ar:Some Artist]\n[ti:Some Title]\n[00:01.00]Real lyric line"
assert parse_lrc(lrc) == [[1.0, "Real lyric line"]]
def test_parse_lrc_skips_lines_with_no_timestamp():
lrc = "just plain text, no timing at all\n[00:03.00]Timed line"
assert parse_lrc(lrc) == [[3.0, "Timed line"]]
def test_parse_lrc_handles_minutes_over_59():
# A 4-minute mark - mm isn't capped at 59, it just keeps counting.
lrc = "[04:30.50]Late in the song"
assert parse_lrc(lrc) == [[270.5, "Late in the song"]]
def test_parse_lrc_timestamp_without_fractional_seconds():
lrc = "[01:00]No fractional part"
assert parse_lrc(lrc) == [[60.0, "No fractional part"]]
def test_parse_lrc_returns_none_for_no_timed_lines():
assert parse_lrc("[ar:Artist]\nplain untimed text") is None
def test_parse_lrc_returns_none_for_empty_string():
assert parse_lrc("") is None
def test_fetch_lyrics_unknown_title_short_circuits(mocker):
search = mocker.patch("src.services.music_identification.syncedlyrics.search")
result = asyncio.run(fetch_lyrics("Unknown Title", "Someone"))
assert result == {"lyrics": None, "synced_lyrics": None}
search.assert_not_called()
def test_fetch_lyrics_prefers_synced_and_derives_plain_text(mocker):
search = mocker.patch(
"src.services.music_identification.syncedlyrics.search",
return_value="[00:01.00]La\n[00:02.50]La la",
)
result = asyncio.run(fetch_lyrics("Song", "Artist"))
assert result == {"lyrics": "La\nLa la", "synced_lyrics": [[1.0, "La"], [2.5, "La la"]]}
# synced_only=True on the first (and in this case only) attempt.
search.assert_called_once_with("Song Artist", synced_only=True)
def test_fetch_lyrics_falls_back_to_plain_when_nothing_synced_exists(mocker):
search = mocker.patch(
"src.services.music_identification.syncedlyrics.search",
side_effect=[None, "plain lyrics\nwith no timing"],
)
result = asyncio.run(fetch_lyrics("Song", "Artist"))
assert result == {"lyrics": "plain lyrics\nwith no timing", "synced_lyrics": None}
assert search.call_count == 2
search.assert_any_call("Song Artist", synced_only=True)
search.assert_any_call("Song Artist")
def test_fetch_lyrics_returns_none_when_nothing_found_anywhere(mocker):
mocker.patch("src.services.music_identification.syncedlyrics.search", side_effect=[None, None])
result = asyncio.run(fetch_lyrics("Song", "Artist"))
assert result == {"lyrics": None, "synced_lyrics": None}
def test_fetch_lyrics_synced_search_error_falls_back_to_plain(mocker):
search = mocker.patch(
"src.services.music_identification.syncedlyrics.search",
side_effect=[Exception("provider down"), "plain lyrics only"],
)
result = asyncio.run(fetch_lyrics("Song", "Artist"))
assert result == {"lyrics": "plain lyrics only", "synced_lyrics": None}
assert search.call_count == 2
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment