"""Song library: upload or YouTube link, list, detail, delete, stem audio, peaks, and stage-2 extraction. Every route only sees the requesting visitor's songs (stemdeck/visitors.py; locally that is every song).""" from __future__ import annotations import asyncio import json import os import re import shutil from pathlib import Path from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile from fastapi.concurrency import run_in_threadpool from fastapi.responses import FileResponse, Response from sqlmodel import Session, col, select from stemdeck import quotas, youtube from stemdeck.api.system import ACCEPTED_EXTENSIONS, extractors_payload from stemdeck.audio_io import AudioError, probe_duration from stemdeck.db import get_session from stemdeck.library import owned_song, remove_song, song_folder from stemdeck.models import TERMINAL_JOB_STATUSES, Job, Song, Stem from stemdeck.schemas import ( ExtractIn, FromUrlIn, JobOut, SongDetailOut, SongSummaryOut, UploadOut, job_out, song_detail, song_summary, ) from stemdeck.settings import get_config, get_settings from stemdeck.visitors import client_key, current_owner router = APIRouter(tags=["songs"]) UPLOAD_CHUNK = 1024 * 1024 SAFE_NAME = re.compile(r"^[a-z0-9_]{1,64}$") CHORDS_FILE = "chords.json" def _limit_hint() -> str: return "" if get_settings().public else " (max_duration_sec in config.yaml)" @router.get("/songs", response_model=list[SongSummaryOut]) def list_songs(session: Session = Depends(get_session), owner: str = Depends(current_owner)) -> list[SongSummaryOut]: songs = session.exec(select(Song).where(Song.owner == owner).order_by(col(Song.created_at).desc())).all() return [song_summary(session, s) for s in songs] @router.post("/songs/upload", response_model=UploadOut, status_code=201) async def upload_song( file: UploadFile = File(...), quality: str = Form("fast"), title: str | None = Form(None), artist: str | None = Form(None), session: Session = Depends(get_session), owner: str = Depends(current_owner), client: str = Depends(client_key), ) -> UploadOut: cfg = get_config() filename = Path(file.filename or "upload") ext = filename.suffix.lower() if ext not in ACCEPTED_EXTENSIONS: allowed = ", ".join(e.lstrip(".") for e in ACCEPTED_EXTENSIONS) raise HTTPException(400, f"Unsupported file type '{ext or '?'}'. Use one of: {allowed}.") if quality not in cfg.qualities: raise HTTPException(400, f"Unknown quality '{quality}'.") quotas.check_can_start(session, owner, client, new_song=True) song = Song(title=(title or filename.stem).strip()[:200] or "Untitled", artist=(artist or "").strip()[:200] or None, quality=quality, original_filename=filename.name[:255], owner=owner, client=client) folder = get_settings().songs_dir / song.id folder.mkdir(parents=True, exist_ok=True) dest = folder / f"original{ext}" limit = cfg.max_upload_mb * 1024 * 1024 size = 0 try: with open(dest, "wb") as out: while chunk := await file.read(UPLOAD_CHUNK): size += len(chunk) if size > limit: raise HTTPException(413, f"File is larger than {cfg.max_upload_mb} MB.") out.write(chunk) if size == 0: raise HTTPException(400, "The uploaded file is empty.") duration = await run_in_threadpool(probe_duration, dest) if duration > cfg.max_duration_sec: raise HTTPException(400, f"This file is {duration / 60:.1f} min long; the limit is " f"{cfg.max_duration_sec / 60:.0f} min{_limit_hint()}.") except AudioError as exc: shutil.rmtree(folder, ignore_errors=True) raise HTTPException(400, str(exc)) from exc except HTTPException: shutil.rmtree(folder, ignore_errors=True) raise song.duration_sec = round(duration, 3) return _queue_split(session, song, {"quality": quality}, client) @router.post("/songs/from-url", response_model=UploadOut, status_code=201) async def song_from_url(body: FromUrlIn, session: Session = Depends(get_session), owner: str = Depends(current_owner), client: str = Depends(client_key)) -> UploadOut: """Check a YouTube link (title, length, sign-in) now; the split job downloads the audio first.""" cfg = get_config() if body.quality not in cfg.qualities: raise HTTPException(400, f"Unknown quality '{body.quality}'.") try: url = youtube.canonical_url(body.url) except youtube.YouTubeError as exc: raise HTTPException(400, str(exc)) from exc quotas.check_can_start(session, owner, client, new_song=True) try: info = await run_in_threadpool(youtube.probe, url) youtube.check_video(info, cfg.max_duration_sec) except youtube.YouTubeError as exc: raise HTTPException(400, str(exc)) from exc title = (body.title or "").strip() or info.title artist = (body.artist or "").strip() or info.artist song = Song(title=title[:200], artist=artist[:200] if artist else None, quality=body.quality, source_type="youtube", source_url=url, original_filename=f"YouTube {info.video_id}", duration_sec=info.duration_sec, owner=owner, client=client) return _queue_split(session, song, {"quality": body.quality, "source_url": url}, client) def _queue_split(session: Session, song: Song, params: dict[str, object], client: str) -> UploadOut: try: with quotas.admit(session, song.owner, client, "split", new_song=True): # checked again, atomically session.add(song) session.commit() job = Job(song_id=song.id, type="split", params=params) session.add(job) session.commit() except HTTPException: shutil.rmtree(get_settings().songs_dir / song.id, ignore_errors=True) raise session.refresh(song) session.refresh(job) return UploadOut(song=song_summary(session, song), job=job_out(session, job)) @router.get("/songs/{song_id}", response_model=SongDetailOut) def get_song(song_id: str, session: Session = Depends(get_session), owner: str = Depends(current_owner)) -> SongDetailOut: song = owned_song(session, song_id, owner) return song_detail(session, song, song_folder(song_id)) @router.delete("/songs/{song_id}", status_code=204) def delete_song(song_id: str, session: Session = Depends(get_session), owner: str = Depends(current_owner)) -> Response: owned_song(session, song_id, owner) song_folder(song_id) # validates the id before anything is deleted remove_song(session, song_id) return Response(status_code=204) @router.get("/songs/{song_id}/stems/{name}") def get_stem_audio(song_id: str, name: str, session: Session = Depends(get_session), owner: str = Depends(current_owner)) -> FileResponse: if not SAFE_NAME.fullmatch(name): raise HTTPException(404, "Stem not found.") owned_song(session, song_id, owner) stem = session.exec(select(Stem).where(Stem.song_id == song_id, Stem.name == name)).first() if stem is None or not Path(stem.file_path).exists(): raise HTTPException(404, "Stem not found.") # URLs carry ?v=, so each version can be cached for good. return FileResponse(stem.file_path, media_type="audio/flac", headers={"Cache-Control": "private, max-age=31536000, immutable"}) _chord_locks: dict[str, asyncio.Lock] = {} def _read_cached_chords(cache: Path) -> list[object] | None: try: return json.loads(cache.read_text(encoding="utf-8")) except FileNotFoundError: return None except (OSError, json.JSONDecodeError): cache.unlink(missing_ok=True) return None @router.get("/songs/{song_id}/chords") async def get_chords(song_id: str, session: Session = Depends(get_session), owner: str = Depends(current_owner)) -> dict[str, object]: """Chord per beat for the mixer's added instruments. Computed once (about 10 s), then cached; an extraction that rewrites stems deletes the cache. Concurrent requests for a song share one computation.""" song = owned_song(session, song_id, owner) if song.status != "ready": raise HTTPException(409, "Wait for the song to finish splitting first.") folder = song_folder(song_id) cache = folder / CHORDS_FILE lock = _chord_locks.setdefault(song_id, asyncio.Lock()) try: async with lock: return await _compute_chords(session, song_id, folder, cache) finally: if not lock.locked(): _chord_locks.pop(song_id, None) # nobody waiting: don't keep a lock per song forever async def _compute_chords(session: Session, song_id: str, folder: Path, cache: Path) -> dict[str, object]: from stemdeck.pipeline.chords import song_chords cached = _read_cached_chords(cache) if cached is not None: return {"chords": cached} try: beats = json.loads((folder / "analysis.json").read_text(encoding="utf-8"))["beats"] except (OSError, json.JSONDecodeError, KeyError) as exc: raise HTTPException(409, "This song has no beat analysis, so its chords can't be detected.") from exc rows = session.exec(select(Stem).where(Stem.song_id == song_id)).all() stems = {s.name: Path(s.file_path) for s in rows} chords = [c.to_dict() for c in await run_in_threadpool(song_chords, stems, beats)] tmp = cache.with_name(f"{CHORDS_FILE}.{os.getpid()}.tmp") tmp.write_text(json.dumps(chords), encoding="utf-8") os.replace(tmp, cache) return {"chords": chords} @router.get("/songs/{song_id}/peaks") def get_peaks(song_id: str, session: Session = Depends(get_session), owner: str = Depends(current_owner)) -> FileResponse: owned_song(session, song_id, owner) path = song_folder(song_id) / "peaks.json" if not path.exists(): raise HTTPException(404, "Waveforms are not ready yet.") return FileResponse(path, media_type="application/json", headers={"Cache-Control": "no-cache"}) @router.post("/songs/{song_id}/extract", response_model=JobOut, status_code=201) def extract(song_id: str, body: ExtractIn, session: Session = Depends(get_session), owner: str = Depends(current_owner), client: str = Depends(client_key)) -> JobOut: song = owned_song(session, song_id, owner) if song.status != "ready": raise HTTPException(409, "Wait for the song to finish splitting first.") extractor = next((e for e in extractors_payload() if e["id"] == body.extractor), None) if extractor is None: raise HTTPException(400, f"Unknown extractor '{body.extractor}'.") if not extractor["available"]: raise HTTPException(409, extractor["reason"] or "This extractor is not available.") if body.source_stem is not None and not SAFE_NAME.fullmatch(body.source_stem): raise HTTPException(400, "Invalid source stem.") duplicate = session.exec(select(Job).where(Job.song_id == song_id, Job.type == "extract", col(Job.status).not_in(TERMINAL_JOB_STATUSES))).all() if any(j.params.get("extractor") == body.extractor for j in duplicate): raise HTTPException(409, "This extraction is already queued or running.") with quotas.admit(session, owner, client, "extract", new_song=False): job = Job(song_id=song_id, type="extract", params={"extractor": body.extractor, "source_stem": body.source_stem, "prompt": body.prompt}) session.add(job) session.commit() session.refresh(job) return job_out(session, job)