Commit a97f9454 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Skip re-tagging/re-storing a song a user already has in their library

Previously, re-uploading (or re-tagging from Telegram) a file already
in your library created a brand new LibrarySong row and a second copy
of the stored file every time - the IdentifiedTrack cache already
skipped re-identifying it, but still re-ran ffmpeg tagging and wrote a
duplicate file, and always inserted a new row. Add a fingerprint
column to library_songs and check it (per-user) before doing any of
that: a match now just hands back the existing entry.

Dedup is per-user and keyed by the same content fingerprint already
used for the IdentifiedTrack cache, not by title/artist text (which
drifts across correction passes and isn't reliable for this).
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent f2a1dce8
Pipeline #1048 passed with stage
in 4 minutes and 59 seconds
"""add fingerprint to library_songs
Revision ID: e9d581074a3f
Revises: d7aa8b954a33
Create Date: 2026-08-10 20:00:55.880540
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'e9d581074a3f'
down_revision: Union[str, Sequence[str], None] = 'd7aa8b954a33'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('library_songs', sa.Column('fingerprint', sa.String(), nullable=True))
op.create_index(op.f('ix_library_songs_fingerprint'), 'library_songs', ['fingerprint'], unique=False)
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_library_songs_fingerprint'), table_name='library_songs')
op.drop_column('library_songs', 'fingerprint')
# ### end Alembic commands ###
......@@ -58,6 +58,36 @@ async def _identify_tag_and_store(
before this existed."""
try:
fingerprint = await compute_fingerprint(raw_file_path)
existing_song = (
db.query(LibrarySong)
.filter(LibrarySong.user_id == current_user.id, LibrarySong.fingerprint == fingerprint)
.first()
if fingerprint else None
)
if existing_song:
# Same user, same recording (by content fingerprint, not just title/artist text) -
# they already have this tagged and stored. Hand back the existing entry instead of
# re-running identification, re-tagging, and writing a second copy of the file.
download_url = str(request.base_url).rstrip('/') + urllib.parse.quote(
storage.url_path_for(existing_song.file_path)
)
return {
"status": "success",
"download_url": download_url,
"metadata": {
"library_song_id": existing_song.id,
"title": existing_song.title,
"artist": existing_song.artist,
"album": existing_song.album,
"genre": existing_song.genre,
"year": "",
"has_lyrics": bool(existing_song.lyrics),
"lyrics": existing_song.lyrics,
"cover_art": existing_song.coverart,
},
}
cached = (
db.query(IdentifiedTrack).filter(IdentifiedTrack.fingerprint == fingerprint).first()
if fingerprint else None
......@@ -129,6 +159,7 @@ async def _identify_tag_and_store(
coverart=candidate.get('coverart', ''),
lyrics=candidate.get('lyrics', ''),
file_path=final_path,
fingerprint=fingerprint,
)
db.add(library_song)
db.commit()
......
......@@ -71,6 +71,10 @@ class LibrarySong(Base):
coverart = Column(String)
lyrics = Column(String)
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/
# artist text matching (which is unreliable across correction passes).
fingerprint = Column(String, index=True, nullable=True)
added_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class Playlist(Base):
......
......@@ -40,6 +40,14 @@ def store_final(user_id: int, local_path: str) -> tuple[str, str]:
return dest, url_path
def url_path_for(local_path: str) -> str:
"""Reverse of store_final's second return value - reconstructs the servable /downloads
URL for a path that was persisted earlier (e.g. LibrarySong.file_path), so callers don't
need to know the on-disk layout themselves."""
rel = os.path.relpath(local_path, DOWNLOADS_DIR)
return f"/downloads/{rel.replace(os.sep, '/')}"
def cleanup_temp(path: str):
if path and os.path.exists(path):
os.remove(path)
......@@ -151,3 +151,76 @@ def test_music_upload_cached_fingerprint_skips_identification(client, db_session
song = db_session.query(LibrarySong).filter(LibrarySong.user_id == user.id).first()
assert song.title == "Cached Title"
def test_music_upload_already_in_library_reuses_existing_song(client, db_session, auth_as, mocker):
"""Re-uploading a file you've already tagged shouldn't create a second LibrarySong, or
even re-run identification/tagging/storage for it - just hand back what's already there."""
headers, user = auth_as()
fingerprint = "fp-user-already-has-this"
existing = LibrarySong(
user_id=user.id,
title="Already Tagged",
artist="Already Artist",
album="Already Album",
genre="Jazz",
coverart=None,
lyrics="existing lyrics",
file_path="./var/storage/downloads/1/existing.mp3",
fingerprint=fingerprint,
)
db_session.add(existing)
db_session.commit()
db_session.refresh(existing)
mocker.patch("src.api.routers.music.compute_fingerprint", return_value=fingerprint)
identify_audio = mocker.patch("src.api.routers.music.identify_audio")
tag_and_convert_audio = mocker.patch("src.api.routers.music.tag_and_convert_audio")
store_final = mocker.patch("src.api.routers.music.storage.store_final")
response = client.post(
"/music/upload",
headers=headers,
files={"file": ("test.mp3", b"fake mp3 bytes", "audio/mpeg")},
)
assert response.status_code == 200
body = response.json()
assert body["metadata"]["library_song_id"] == existing.id
assert body["metadata"]["title"] == "Already Tagged"
assert body["download_url"].endswith("/downloads/1/existing.mp3")
identify_audio.assert_not_called()
tag_and_convert_audio.assert_not_called()
store_final.assert_not_called()
songs = db_session.query(LibrarySong).filter(LibrarySong.user_id == user.id).all()
assert len(songs) == 1
def test_music_upload_same_fingerprint_different_users_both_get_their_own_song(client, db_session, auth_as, mocker):
"""Dedup is per-user - two different users uploading the same recording should each end up
with their own LibrarySong (identification can still be skipped via the IdentifiedTrack
cache, but the library row itself isn't shared)."""
headers_a, user_a = auth_as()
headers_b, user_b = auth_as()
fingerprint = "fp-shared-recording"
db_session.add(LibrarySong(
user_id=user_a.id, title="Shared Song", artist="Shared Artist", album="", genre="",
coverart=None, lyrics=None, file_path="./var/storage/downloads/a/shared.mp3", fingerprint=fingerprint,
))
db_session.commit()
_mock_pipeline(mocker, fingerprint=fingerprint)
response = client.post(
"/music/upload",
headers=headers_b,
files={"file": ("test.mp3", b"fake mp3 bytes", "audio/mpeg")},
)
assert response.status_code == 200
songs_b = db_session.query(LibrarySong).filter(LibrarySong.user_id == user_b.id).all()
assert len(songs_b) == 1
songs_a = db_session.query(LibrarySong).filter(LibrarySong.user_id == user_a.id).all()
assert len(songs_a) == 1
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