Commit b1f5d610 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Discovery: give a match from any user's library, real confidence field; rate limit /remix

Discovery hits now check the whole app's library (not just the caller's own) - if
someone else (including a super-admin seed upload) already has the song, the finder
gets their own LibrarySong row immediately, reusing the existing file_path rather
than duplicating audio on disk. The library is built entirely from real uploads,
never anything auto-downloaded, so this stays clear of the copyright concern raised
earlier.

AcoustID's match score and a fixed value for Shazam are now a real queryable
confidence field on DiscoveredSong instead of embedded in a source string.

POST /remix had no rate limiting despite being the one genuinely expensive endpoint
(real Gemini spend + CPU-bound Demucs per call) - added the same DB-backed limiter
pattern used elsewhere, reusing RemixJob.created_at as its own counter.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent b7f372fd
Pipeline #1138 passed with stage
in 19 minutes and 2 seconds
"""add confidence and source to discovered_songs
Revision ID: 9f59c50ce5ca
Revises: f3514f910205
Create Date: 2026-08-28 10:38:49.364291
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '9f59c50ce5ca'
down_revision: Union[str, Sequence[str], None] = 'f3514f910205'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
op.add_column('discovered_songs', sa.Column('confidence', sa.Float(), nullable=True))
op.add_column('discovered_songs', sa.Column('source', sa.String(), nullable=True))
def downgrade() -> None:
"""Downgrade schema."""
op.drop_column('discovered_songs', 'source')
op.drop_column('discovered_songs', 'confidence')
import shutil
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form, status
from sqlalchemy import func
from sqlalchemy.orm import Session
from datetime import datetime, timedelta, timezone
......@@ -28,6 +29,55 @@ def _check_identify_rate_limit(db: Session, user_id: int):
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="Too many identify requests, try again later")
def _find_library_match(db: Session, title: str, artist: str, user_id: int | None = None) -> LibrarySong | None:
"""Case/whitespace-insensitive title+artist lookup - scoped to one user's library if
user_id is given, otherwise searched across every user's library (used to find something
to give a caller who doesn't have it themselves yet)."""
query = db.query(LibrarySong).filter(
func.lower(func.trim(LibrarySong.title)) == title.strip().lower(),
func.lower(func.trim(LibrarySong.artist)) == artist.strip().lower(),
)
if user_id is not None:
query = query.filter(LibrarySong.user_id == user_id)
return query.first()
def _give_from_shared_library(db: Session, current_user: User, title: str, artist: str) -> int | None:
"""The app's library is the collective pool of everything every user (including a super
admin seeding popular tracks) has uploaded and tagged - never anything auto-downloaded
from an external source. If a Discovery hit matches a song already sitting in *anyone's*
library and the caller doesn't have their own copy yet, give them one immediately: a new
LibrarySong row of their own (so it shows up in their Library, is playlist-able, etc.),
reusing the same file_path rather than duplicating the audio on disk. Returns the
resulting library_song_id, or None if nobody has this song at all yet."""
if not title or not artist or title == "Unknown" or artist == "Unknown":
return None
own = _find_library_match(db, title, artist, user_id=current_user.id)
if own:
return own.id
source_song = _find_library_match(db, title, artist)
if not source_song:
return None
given = LibrarySong(
user_id=current_user.id,
title=source_song.title,
artist=source_song.artist,
album=source_song.album,
genre=source_song.genre,
coverart=source_song.coverart,
lyrics=source_song.lyrics,
file_path=source_song.file_path,
fingerprint=source_song.fingerprint,
)
db.add(given)
db.commit()
db.refresh(given)
return given.id
@router.post("/listen")
async def discovery_listen(file: UploadFile = File(...), db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
"""Accepts a short audio snippet from the microphone to identify what's playing."""
......@@ -51,13 +101,17 @@ async def discovery_listen(file: UploadFile = File(...), db: Session = Depends(g
title=candidate.get("title"),
artist=candidate.get("artist"),
genre=candidate.get("genre"),
coverart=candidate.get("coverart")
coverart=candidate.get("coverart"),
confidence=candidate.get("confidence"),
source=candidate.get("source"),
)
db.add(new_song)
db.commit()
db.refresh(new_song)
return {"status": "success", "detected": candidate, "discovery_id": new_song.id}
library_song_id = _give_from_shared_library(db, current_user, candidate.get("title"), candidate.get("artist"))
return {"status": "success", "detected": candidate, "discovery_id": new_song.id, "library_song_id": library_song_id}
finally:
storage.cleanup_temp(temp_path)
......@@ -94,6 +148,8 @@ async def discovery_history(db: Session = Depends(get_db), current_user: User =
"artist": song.artist,
"genre": song.genre,
"coverart": song.coverart,
"confidence": song.confidence,
"source": song.source,
"detected_at": song.detected_at,
"liked": song.liked,
"library_song_id": library_index.get(((song.title or "").strip().lower(), (song.artist or "").strip().lower())),
......
......@@ -2,9 +2,10 @@ import json
import os
import shutil
import uuid
from datetime import datetime, timedelta, timezone
from typing import List, Optional
from fastapi import APIRouter, BackgroundTasks, Depends, File, Form, HTTPException, UploadFile
from fastapi import APIRouter, BackgroundTasks, Depends, File, Form, HTTPException, UploadFile, status
from sqlalchemy.orm import Session
from src.core.database import LibrarySong, RemixJob, User, get_db
......@@ -17,6 +18,25 @@ router = APIRouter(prefix="/remix", tags=["AI Remix"])
MAX_SONGS = 5
TEMP_DIR = storage.TEMP_DIR
# Unlike everything else in this app, a single accepted job is genuinely expensive - real
# Gemini API spend plus minutes of CPU-bound Demucs stem separation - so this is deliberately
# far stricter than the identify-audio-style limits elsewhere. Reuses RemixJob.created_at as
# its own counter (a row is only ever inserted after validation passes, below) rather than a
# separate *Attempt table, since every accepted request already leaves exactly one row here.
MAX_REMIX_JOBS_PER_USER = 5
REMIX_WINDOW = timedelta(hours=1)
def _check_remix_rate_limit(db: Session, user_id: int):
now = datetime.now(timezone.utc).replace(tzinfo=None)
count = (
db.query(RemixJob)
.filter(RemixJob.user_id == user_id, RemixJob.created_at >= now - REMIX_WINDOW)
.count()
)
if count >= MAX_REMIX_JOBS_PER_USER:
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="Too many remix jobs, try again later")
@router.post("")
async def create_remix(
......@@ -27,6 +47,8 @@ async def create_remix(
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
_check_remix_rate_limit(db, current_user.id)
# Deliberately does nothing here except fast local I/O (save uploads, look up library
# rows) - no identify_audio/Shazam/AcoustID calls. Those are real network calls that can
# take ~30s each to time out, and doing them here would block this response for
......
......@@ -82,6 +82,12 @@ class DiscoveredSong(Base):
coverart = Column(String)
detected_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
liked = Column(Boolean, default=None, nullable=True)
# 0-100, nullable - not every identification source can produce a real number. AcoustID
# gives one natively; Shazam doesn't expose one at all (a returned match is already a high-
# confidence fingerprint hit, so it's given a fixed value rather than left blank); Gemini's
# transcription-based guess has no comparable signal, so it stays null.
confidence = Column(Float, nullable=True)
source = Column(String, nullable=True) # "Shazam" | "AcoustID" | "Gemini AI"
class LibrarySong(Base):
__tablename__ = "library_songs"
......
......@@ -55,7 +55,11 @@ async def identify_audio(file_path: str) -> list:
candidates.append({
'title': title, 'artist': artist, 'album': album, 'year': year, 'genre': genre,
'track_number': '1/1', 'source': 'Shazam', 'coverart': coverart_url, 'lyrics': lyrics
'track_number': '1/1', 'source': 'Shazam', 'coverart': coverart_url, 'lyrics': lyrics,
# Shazam's API doesn't expose a match score - a returned result is already a
# real audio-fingerprint hit (not a fuzzy guess), so it's given a fixed
# high-confidence value rather than left blank.
'confidence': 95.0,
})
except Exception as e:
logger.error(f"Shazam error: {e}")
......@@ -81,7 +85,8 @@ async def identify_audio(file_path: str) -> list:
candidates.append({
'title': title, 'artist': artist, 'album': album, 'year': year, 'genre': genre,
'track_number': track_number, 'source': f'AcoustID ({int(score*100)}%)', 'coverart': None, 'lyrics': None
'track_number': track_number, 'source': 'AcoustID', 'coverart': None, 'lyrics': None,
'confidence': round(score * 100, 1),
})
if len(candidates) >= 4: break
except Exception as e:
......@@ -138,7 +143,10 @@ async def identify_with_gemini(file_path: str, lang_pref: str) -> dict:
'track_number': '1/1',
'source': 'Gemini AI',
'coverart': None,
'lyrics': data.get('lyrics', '')
'lyrics': data.get('lyrics', ''),
# No comparable score for a transcription-based guess - stays null rather than a
# made-up number, distinct from the two fingerprint-based sources above.
'confidence': None,
}
except Exception as e:
logger.error(f"Gemini identification failed: {e}")
......
......@@ -104,6 +104,89 @@ def test_discovery_listen_success_creates_row(client, db_session, auth_as, monke
assert row.artist == "Dummy Artist"
def test_discovery_listen_persists_confidence_and_source(client, db_session, auth_as, monkeypatch):
headers, _ = auth_as()
async def _fake_identify_hit(path):
return [{"title": "Song", "artist": "Artist", "genre": "Pop", "coverart": None, "confidence": 87.5, "source": "AcoustID"}]
monkeypatch.setattr(discovery_router, "identify_audio", _fake_identify_hit)
response = client.post("/discovery/listen", headers=headers, files={"file": _dummy_audio_file()})
body = response.json()
assert body["detected"]["confidence"] == 87.5
row = db_session.query(DiscoveredSong).filter(DiscoveredSong.id == body["discovery_id"]).first()
assert row.confidence == 87.5
assert row.source == "AcoustID"
def test_discovery_history_includes_confidence_and_source(client, db_session, auth_as):
headers, user = auth_as()
db_session.add(DiscoveredSong(user_id=user.id, title="Song A", artist="Artist A", confidence=95.0, source="Shazam"))
db_session.commit()
response = client.get("/discovery/history", headers=headers)
entry = response.json()["history"][0]
assert entry["confidence"] == 95.0
assert entry["source"] == "Shazam"
def test_discovery_listen_gives_a_song_already_in_someone_elses_library(client, db_session, auth_as, monkeypatch):
# The app's library is a collective pool built from every user's (and super admin's)
# uploads - a Discovery hit matching a song someone else already has should hand the
# finder their own copy immediately, not leave them with nothing playable.
headers, finder = auth_as()
_, contributor = auth_as()
db_session.add(LibrarySong(
user_id=contributor.id, title="Shared Song", artist="Shared Artist", genre="Pop",
coverart="http://example.com/art.jpg", file_path="/data/shared-song.mp3", fingerprint="abc123",
))
db_session.commit()
async def _fake_identify_hit(path):
return [{"title": "Shared Song", "artist": "Shared Artist", "genre": "Pop", "coverart": None}]
monkeypatch.setattr(discovery_router, "identify_audio", _fake_identify_hit)
response = client.post("/discovery/listen", headers=headers, files={"file": _dummy_audio_file()})
body = response.json()
assert body["library_song_id"] is not None
given = db_session.query(LibrarySong).filter(LibrarySong.id == body["library_song_id"]).first()
assert given.user_id == finder.id
assert given.file_path == "/data/shared-song.mp3" # reused, not duplicated on disk
assert given.fingerprint == "abc123"
def test_discovery_listen_does_not_duplicate_a_song_the_finder_already_has(client, db_session, auth_as, monkeypatch):
headers, finder = auth_as()
existing = LibrarySong(user_id=finder.id, title="Already Mine", artist="Someone", genre="Pop", file_path="/data/mine.mp3")
db_session.add(existing)
db_session.commit()
db_session.refresh(existing)
async def _fake_identify_hit(path):
return [{"title": "Already Mine", "artist": "Someone", "genre": "Pop", "coverart": None}]
monkeypatch.setattr(discovery_router, "identify_audio", _fake_identify_hit)
response = client.post("/discovery/listen", headers=headers, files={"file": _dummy_audio_file()})
body = response.json()
assert body["library_song_id"] == existing.id
count = db_session.query(LibrarySong).filter(LibrarySong.user_id == finder.id).count()
assert count == 1
def test_discovery_listen_no_library_song_id_when_nobody_has_it(client, auth_as, monkeypatch):
headers, _ = auth_as()
async def _fake_identify_hit(path):
return [{"title": "Totally New Song", "artist": "Nobody Yet", "genre": "Pop", "coverart": None}]
monkeypatch.setattr(discovery_router, "identify_audio", _fake_identify_hit)
response = client.post("/discovery/listen", headers=headers, files={"file": _dummy_audio_file()})
assert response.json()["library_song_id"] is None
def test_discovery_listen_no_match(client, auth_as, monkeypatch):
headers, _ = auth_as()
......
......@@ -62,6 +62,53 @@ def test_remix_rejects_more_than_five_songs(client, auth_as, monkeypatch):
assert response.status_code == 400
def test_remix_rate_limited_after_too_many_jobs(client, auth_as, monkeypatch):
headers, _ = auth_as()
monkeypatch.setattr(remix_router, "render_remix_sync", lambda *a, **kw: None)
monkeypatch.setattr(remix_router, "MAX_REMIX_JOBS_PER_USER", 2)
for _ in range(2):
files = [("files", ("song.wav", io.BytesIO(_wav_bytes()), "audio/wav"))]
response = client.post("/remix", data={"prompt": "mashup"}, files=files, headers=headers)
assert response.status_code == 200
files = [("files", ("song.wav", io.BytesIO(_wav_bytes()), "audio/wav"))]
response = client.post("/remix", data={"prompt": "mashup"}, files=files, headers=headers)
assert response.status_code == 429
def test_remix_rate_limit_is_per_user(client, auth_as, monkeypatch):
headers_a, _ = auth_as()
headers_b, _ = auth_as()
monkeypatch.setattr(remix_router, "render_remix_sync", lambda *a, **kw: None)
monkeypatch.setattr(remix_router, "MAX_REMIX_JOBS_PER_USER", 1)
files = [("files", ("song.wav", io.BytesIO(_wav_bytes()), "audio/wav"))]
client.post("/remix", data={"prompt": "mashup"}, files=files, headers=headers_a)
files = [("files", ("song.wav", io.BytesIO(_wav_bytes()), "audio/wav"))]
limited = client.post("/remix", data={"prompt": "mashup"}, files=files, headers=headers_a)
assert limited.status_code == 429
files = [("files", ("song.wav", io.BytesIO(_wav_bytes()), "audio/wav"))]
response = client.post("/remix", data={"prompt": "mashup"}, files=files, headers=headers_b)
assert response.status_code == 200
def test_remix_rejected_validation_does_not_count_toward_rate_limit(client, auth_as, monkeypatch):
# A 400 (too many songs, bad request) never inserts a RemixJob row, so it must not eat
# into the same budget as a genuinely accepted, expensive job.
headers, _ = auth_as()
monkeypatch.setattr(remix_router, "render_remix_sync", lambda *a, **kw: None)
monkeypatch.setattr(remix_router, "MAX_REMIX_JOBS_PER_USER", 1)
response = client.post("/remix", data={"prompt": "make it slower"}, files=[], headers=headers)
assert response.status_code == 400
files = [("files", ("song.wav", io.BytesIO(_wav_bytes()), "audio/wav"))]
response = client.post("/remix", data={"prompt": "mashup"}, files=files, headers=headers)
assert response.status_code == 200
def test_remix_does_not_call_identify_audio_before_responding(client, auth_as, monkeypatch):
# The whole point of the earlier fix: identify_audio (real Shazam/AcoustID network
# calls, ~30s each on a miss) must never run inside the request/response cycle - only
......
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