Upload files to "kronic/resolver"
This commit is contained in:
@@ -0,0 +1,656 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import re
|
||||
import threading
|
||||
from typing import Any
|
||||
from difflib import SequenceMatcher
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
try:
|
||||
from spotdl.download.downloader import Downloader as SpotDLDownloader
|
||||
from spotdl.utils.search import (
|
||||
get_simple_songs as spotdl_get_simple_songs,
|
||||
get_search_results as spotdl_get_search_results,
|
||||
)
|
||||
from spotdl.utils.spotify import SpotifyClient as SpotDLSpotifyClient
|
||||
|
||||
SPOTDL_AVAILABLE = True
|
||||
SPOTDL_IMPORT_ERROR = None
|
||||
except Exception as error:
|
||||
SpotDLDownloader = None
|
||||
spotdl_get_simple_songs = None
|
||||
spotdl_get_search_results = None
|
||||
SpotDLSpotifyClient = None
|
||||
SPOTDL_AVAILABLE = False
|
||||
SPOTDL_IMPORT_ERROR = error
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
SPOTDL_MAX_ITEMS = max(
|
||||
1,
|
||||
int(os.getenv("KRONIC_SPOTDL_MAX_ITEMS", "500")),
|
||||
)
|
||||
|
||||
SPOTDL_AUDIO_PROVIDERS = [
|
||||
value.strip()
|
||||
for value in os.getenv(
|
||||
"KRONIC_SPOTDL_AUDIO_PROVIDERS",
|
||||
"youtube-music,youtube",
|
||||
).split(",")
|
||||
if value.strip()
|
||||
]
|
||||
|
||||
SPOTDL_CLIENT_ID = os.getenv(
|
||||
"SPOTIPY_CLIENT_ID",
|
||||
"",
|
||||
).strip()
|
||||
|
||||
SPOTDL_CLIENT_SECRET = os.getenv(
|
||||
"SPOTIPY_CLIENT_SECRET",
|
||||
"",
|
||||
).strip()
|
||||
|
||||
_SPOTDL_LOCK = threading.Lock()
|
||||
_SPOTDL_READY = False
|
||||
_SPOTDL_DOWNLOADER = None
|
||||
_SPOTDL_MATCH_CACHE: dict[str, str] = {}
|
||||
|
||||
|
||||
def _spotify_source_kind(value: str) -> str:
|
||||
match = re.search(
|
||||
r"open\.spotify\.com/(track|album|playlist|artist)/",
|
||||
value or "",
|
||||
re.I,
|
||||
)
|
||||
return match.group(1).lower() if match else "search"
|
||||
|
||||
|
||||
def _youtube_id(value: str) -> str:
|
||||
value = str(value or "")
|
||||
|
||||
patterns = (
|
||||
r"(?:youtu\.be/)([A-Za-z0-9_-]{6,})",
|
||||
r"(?:[?&]v=)([A-Za-z0-9_-]{6,})",
|
||||
r"(?:youtube\.com/embed/)([A-Za-z0-9_-]{6,})",
|
||||
r"(?:music\.youtube\.com/watch\?v=)([A-Za-z0-9_-]{6,})",
|
||||
)
|
||||
|
||||
for pattern in patterns:
|
||||
match = re.search(pattern, value)
|
||||
if match:
|
||||
return match.group(1)
|
||||
|
||||
return ""
|
||||
|
||||
|
||||
def _song_value(
|
||||
data: dict[str, Any],
|
||||
*names: str,
|
||||
default=None,
|
||||
):
|
||||
for name in names:
|
||||
value = data.get(name)
|
||||
|
||||
if value not in (None, "", []):
|
||||
return value
|
||||
|
||||
return default
|
||||
|
||||
|
||||
def _ensure_spotdl():
|
||||
global _SPOTDL_READY
|
||||
global _SPOTDL_DOWNLOADER
|
||||
|
||||
if not SPOTDL_AVAILABLE:
|
||||
raise RuntimeError(
|
||||
"spotDL is not installed in the resolver environment: "
|
||||
f"{SPOTDL_IMPORT_ERROR}"
|
||||
)
|
||||
|
||||
with _SPOTDL_LOCK:
|
||||
if (
|
||||
_SPOTDL_READY
|
||||
and _SPOTDL_DOWNLOADER is not None
|
||||
):
|
||||
return _SPOTDL_DOWNLOADER
|
||||
|
||||
init_kwargs = {}
|
||||
|
||||
if SPOTDL_CLIENT_ID:
|
||||
init_kwargs["client_id"] = SPOTDL_CLIENT_ID
|
||||
|
||||
if SPOTDL_CLIENT_SECRET:
|
||||
init_kwargs["client_secret"] = SPOTDL_CLIENT_SECRET
|
||||
|
||||
# spotDL 4.5 defaults to its free Spotify metadata path when official
|
||||
# credentials are not supplied.
|
||||
SpotDLSpotifyClient.init(**init_kwargs)
|
||||
|
||||
_SPOTDL_DOWNLOADER = SpotDLDownloader(
|
||||
settings={
|
||||
"audio_providers": (
|
||||
SPOTDL_AUDIO_PROVIDERS
|
||||
or ["youtube-music", "youtube"]
|
||||
),
|
||||
"lyrics_providers": [],
|
||||
"format": "m4a",
|
||||
"save_file": None,
|
||||
}
|
||||
)
|
||||
|
||||
_SPOTDL_READY = True
|
||||
|
||||
return _SPOTDL_DOWNLOADER
|
||||
|
||||
|
||||
def _song_json(song) -> dict[str, Any]:
|
||||
data = getattr(song, "json", None)
|
||||
|
||||
if callable(data):
|
||||
data = data()
|
||||
|
||||
if isinstance(data, dict):
|
||||
return dict(data)
|
||||
|
||||
return {}
|
||||
|
||||
|
||||
|
||||
def _norm_text(value: str) -> str:
|
||||
value = re.sub(r"\([^)]*\)|\[[^\]]*\]", " ", str(value or "").lower())
|
||||
value = re.sub(r"\b(official|audio|video|lyrics?|visualizer|remaster(?:ed)?|hd|4k)\b", " ", value)
|
||||
value = re.sub(r"[^a-z0-9]+", " ", value)
|
||||
return " ".join(value.split())
|
||||
|
||||
|
||||
def _spotify_metadata_item(song) -> dict[str, Any]:
|
||||
data = _song_json(song)
|
||||
artists = _song_value(data, "artists", default=[])
|
||||
if isinstance(artists, str):
|
||||
artists = [artists]
|
||||
artist = str(_song_value(data, "artist", default="") or "")
|
||||
if not artist and artists:
|
||||
artist = str(artists[0])
|
||||
|
||||
return {
|
||||
"spotify_id": str(_song_value(data, "song_id", "track_id", default="") or ""),
|
||||
"spotify_url": str(_song_value(data, "url", default="") or ""),
|
||||
"title": str(_song_value(data, "name", "title", default="") or ""),
|
||||
"artist": artist,
|
||||
"artists": artists,
|
||||
"album": str(_song_value(data, "album_name", "album", default="") or ""),
|
||||
"duration": _song_value(data, "duration", "duration_seconds"),
|
||||
"cover": str(_song_value(data, "cover_url", "cover", default="") or ""),
|
||||
"year": _song_value(data, "year"),
|
||||
"isrc": str(_song_value(data, "isrc", default="") or ""),
|
||||
}
|
||||
|
||||
|
||||
def _spotify_metadata_score(
|
||||
candidate: dict[str, Any],
|
||||
title: str,
|
||||
artist: str,
|
||||
duration: float | None,
|
||||
) -> float:
|
||||
title_score = SequenceMatcher(
|
||||
None,
|
||||
_norm_text(title),
|
||||
_norm_text(candidate.get("title")),
|
||||
).ratio()
|
||||
|
||||
artist_text = " ".join(
|
||||
[
|
||||
str(candidate.get("artist") or ""),
|
||||
*[str(x) for x in candidate.get("artists") or []],
|
||||
]
|
||||
)
|
||||
if artist:
|
||||
artist_score = SequenceMatcher(
|
||||
None,
|
||||
_norm_text(artist),
|
||||
_norm_text(artist_text),
|
||||
).ratio()
|
||||
else:
|
||||
artist_score = 0.7
|
||||
|
||||
duration_score = 0.7
|
||||
try:
|
||||
requested_duration = float(duration or 0)
|
||||
candidate_duration = float(candidate.get("duration") or 0)
|
||||
if requested_duration > 0 and candidate_duration > 0:
|
||||
delta = abs(requested_duration - candidate_duration)
|
||||
duration_score = max(0.0, 1.0 - min(delta, 30.0) / 30.0)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
|
||||
return round(
|
||||
title_score * 0.58
|
||||
+ artist_score * 0.30
|
||||
+ duration_score * 0.12,
|
||||
4,
|
||||
)
|
||||
|
||||
|
||||
def _spotify_metadata_search_sync(
|
||||
title: str,
|
||||
artist: str = "",
|
||||
duration: float | None = None,
|
||||
limit: int = 8,
|
||||
) -> dict[str, Any]:
|
||||
_ensure_spotdl()
|
||||
|
||||
title = str(title or "").strip()
|
||||
artist = str(artist or "").strip()
|
||||
if not title:
|
||||
raise ValueError("title is required")
|
||||
|
||||
query = " ".join(x for x in (artist, title) if x).strip()
|
||||
songs = list(spotdl_get_search_results(query) or [])[:max(1, min(int(limit or 8), 20))]
|
||||
|
||||
candidates = []
|
||||
for song in songs:
|
||||
item = _spotify_metadata_item(song)
|
||||
if not item.get("title"):
|
||||
continue
|
||||
item["score"] = _spotify_metadata_score(item, title, artist, duration)
|
||||
candidates.append(item)
|
||||
|
||||
candidates.sort(key=lambda item: float(item.get("score") or 0), reverse=True)
|
||||
best = candidates[0] if candidates else None
|
||||
|
||||
return {
|
||||
"query": query,
|
||||
"best": best,
|
||||
"candidates": candidates,
|
||||
}
|
||||
|
||||
|
||||
def _resolve_spotify_sync(
|
||||
query: str,
|
||||
limit: int,
|
||||
) -> dict[str, Any]:
|
||||
query = str(query or "").strip()
|
||||
|
||||
if not query:
|
||||
raise ValueError(
|
||||
"Spotify URL or music query is required"
|
||||
)
|
||||
|
||||
downloader = _ensure_spotdl()
|
||||
|
||||
songs = spotdl_get_simple_songs(
|
||||
[query],
|
||||
playlist_retain_track_cover=True,
|
||||
)
|
||||
|
||||
limit = max(
|
||||
1,
|
||||
min(
|
||||
int(limit or SPOTDL_MAX_ITEMS),
|
||||
SPOTDL_MAX_ITEMS,
|
||||
),
|
||||
)
|
||||
|
||||
songs = list(songs or [])[:limit]
|
||||
|
||||
items = []
|
||||
errors = []
|
||||
|
||||
for position, song in enumerate(
|
||||
songs,
|
||||
start=1,
|
||||
):
|
||||
data = _song_json(song)
|
||||
|
||||
spotify_url = str(
|
||||
_song_value(
|
||||
data,
|
||||
"url",
|
||||
default="",
|
||||
)
|
||||
or ""
|
||||
)
|
||||
|
||||
spotify_id = str(
|
||||
_song_value(
|
||||
data,
|
||||
"song_id",
|
||||
"track_id",
|
||||
default="",
|
||||
)
|
||||
or ""
|
||||
)
|
||||
|
||||
cache_key = (
|
||||
spotify_id
|
||||
or spotify_url
|
||||
or (
|
||||
f"{data.get('artist', '')}::"
|
||||
f"{data.get('name', '')}"
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
youtube_url = _SPOTDL_MATCH_CACHE.get(
|
||||
cache_key
|
||||
)
|
||||
|
||||
if not youtube_url:
|
||||
youtube_url = str(
|
||||
downloader.search(song)
|
||||
or ""
|
||||
)
|
||||
|
||||
if youtube_url:
|
||||
_SPOTDL_MATCH_CACHE[
|
||||
cache_key
|
||||
] = youtube_url
|
||||
|
||||
video_id = _youtube_id(
|
||||
youtube_url
|
||||
)
|
||||
|
||||
if not video_id:
|
||||
raise LookupError(
|
||||
"spotDL match did not contain "
|
||||
"a YouTube video ID: "
|
||||
f"{youtube_url}"
|
||||
)
|
||||
|
||||
artists = _song_value(
|
||||
data,
|
||||
"artists",
|
||||
default=[],
|
||||
)
|
||||
|
||||
if isinstance(
|
||||
artists,
|
||||
str,
|
||||
):
|
||||
artists = [artists]
|
||||
|
||||
artist = str(
|
||||
_song_value(
|
||||
data,
|
||||
"artist",
|
||||
default="",
|
||||
)
|
||||
or ""
|
||||
)
|
||||
|
||||
if not artist and artists:
|
||||
artist = str(
|
||||
artists[0]
|
||||
)
|
||||
|
||||
items.append(
|
||||
{
|
||||
"spotify_id": spotify_id,
|
||||
"spotify_url": spotify_url,
|
||||
"title": str(
|
||||
_song_value(
|
||||
data,
|
||||
"name",
|
||||
"title",
|
||||
default=video_id,
|
||||
)
|
||||
),
|
||||
"artist": artist,
|
||||
"artists": artists,
|
||||
"album": str(
|
||||
_song_value(
|
||||
data,
|
||||
"album_name",
|
||||
"album",
|
||||
default="",
|
||||
)
|
||||
or ""
|
||||
),
|
||||
"duration": _song_value(
|
||||
data,
|
||||
"duration",
|
||||
"duration_seconds",
|
||||
),
|
||||
"cover": str(
|
||||
_song_value(
|
||||
data,
|
||||
"cover_url",
|
||||
"cover",
|
||||
default="",
|
||||
)
|
||||
or ""
|
||||
),
|
||||
"year": _song_value(
|
||||
data,
|
||||
"year",
|
||||
),
|
||||
"isrc": str(
|
||||
_song_value(
|
||||
data,
|
||||
"isrc",
|
||||
default="",
|
||||
)
|
||||
or ""
|
||||
),
|
||||
"list_name": str(
|
||||
_song_value(
|
||||
data,
|
||||
"list_name",
|
||||
default="",
|
||||
)
|
||||
or ""
|
||||
),
|
||||
"list_position": (
|
||||
_song_value(
|
||||
data,
|
||||
"list_position",
|
||||
default=position,
|
||||
)
|
||||
),
|
||||
"list_length": (
|
||||
_song_value(
|
||||
data,
|
||||
"list_length",
|
||||
)
|
||||
),
|
||||
"youtube_url": youtube_url,
|
||||
"youtube_id": video_id,
|
||||
"source": "spotdl",
|
||||
}
|
||||
)
|
||||
|
||||
except Exception as error:
|
||||
errors.append(
|
||||
{
|
||||
"position": position,
|
||||
"title": str(
|
||||
_song_value(
|
||||
data,
|
||||
"name",
|
||||
"title",
|
||||
default="Unknown",
|
||||
)
|
||||
),
|
||||
"artist": str(
|
||||
_song_value(
|
||||
data,
|
||||
"artist",
|
||||
default="",
|
||||
)
|
||||
or ""
|
||||
),
|
||||
"error": str(error),
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"query": query,
|
||||
"source_type": _spotify_source_kind(
|
||||
query
|
||||
),
|
||||
"count": len(items),
|
||||
"items": items,
|
||||
"errors": errors,
|
||||
"spotdl": True,
|
||||
}
|
||||
|
||||
|
||||
def _exact_spotify_track_metadata_sync(url: str) -> dict[str, Any]:
|
||||
_ensure_spotdl()
|
||||
url = str(url or "").strip()
|
||||
if not url:
|
||||
raise ValueError("Spotify track URL is required")
|
||||
|
||||
songs = list(
|
||||
spotdl_get_simple_songs(
|
||||
[url],
|
||||
playlist_retain_track_cover=True,
|
||||
)
|
||||
or []
|
||||
)
|
||||
if not songs:
|
||||
raise LookupError("Spotify returned no track metadata")
|
||||
|
||||
song = songs[0]
|
||||
data = _song_json(song)
|
||||
artists = _song_value(data, "artists", default=[])
|
||||
if isinstance(artists, str):
|
||||
artists = [artists]
|
||||
artist = str(_song_value(data, "artist", default="") or "")
|
||||
if not artist and artists:
|
||||
artist = str(artists[0])
|
||||
|
||||
return {
|
||||
"spotify_id": str(_song_value(data, "song_id", "track_id", default="") or ""),
|
||||
"spotify_url": str(_song_value(data, "url", default=url) or url),
|
||||
"title": str(_song_value(data, "name", "title", default="") or ""),
|
||||
"artist": artist,
|
||||
"artists": artists,
|
||||
"album": str(_song_value(data, "album_name", "album", default="") or ""),
|
||||
"duration": _song_value(data, "duration", "duration_seconds"),
|
||||
"cover": str(_song_value(data, "cover_url", "cover", default="") or ""),
|
||||
"year": _song_value(data, "year"),
|
||||
"isrc": str(_song_value(data, "isrc", default="") or ""),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/api/music/spotify/track-metadata")
|
||||
async def spotify_track_metadata(
|
||||
body: dict[str, Any],
|
||||
) -> JSONResponse:
|
||||
url = str(body.get("url") or "").strip()
|
||||
try:
|
||||
track = await asyncio.to_thread(
|
||||
_exact_spotify_track_metadata_sync,
|
||||
url,
|
||||
)
|
||||
except ValueError as error:
|
||||
raise HTTPException(status_code=400, detail=str(error)) from error
|
||||
except Exception as error:
|
||||
raise HTTPException(
|
||||
status_code=502,
|
||||
detail=f"Spotify exact metadata lookup failed: {error}",
|
||||
) from error
|
||||
|
||||
return JSONResponse({"track": track})
|
||||
|
||||
|
||||
@router.get(
|
||||
"/api/music/spotdl/status"
|
||||
)
|
||||
async def spotdl_status() -> JSONResponse:
|
||||
return JSONResponse(
|
||||
{
|
||||
"available": SPOTDL_AVAILABLE,
|
||||
"error": (
|
||||
str(SPOTDL_IMPORT_ERROR)
|
||||
if SPOTDL_IMPORT_ERROR
|
||||
else None
|
||||
),
|
||||
"audio_providers": (
|
||||
SPOTDL_AUDIO_PROVIDERS
|
||||
),
|
||||
"max_items": SPOTDL_MAX_ITEMS,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/api/music/spotify/metadata"
|
||||
)
|
||||
async def spotify_metadata(
|
||||
body: dict[str, Any],
|
||||
) -> JSONResponse:
|
||||
title = str(body.get("title") or "").strip()
|
||||
artist = str(body.get("artist") or "").strip()
|
||||
duration = body.get("duration")
|
||||
|
||||
try:
|
||||
data = await asyncio.to_thread(
|
||||
_spotify_metadata_search_sync,
|
||||
title,
|
||||
artist,
|
||||
duration,
|
||||
int(body.get("limit") or 8),
|
||||
)
|
||||
except ValueError as error:
|
||||
raise HTTPException(status_code=400, detail=str(error)) from error
|
||||
except Exception as error:
|
||||
raise HTTPException(
|
||||
status_code=502,
|
||||
detail=f"Spotify metadata lookup failed: {error}",
|
||||
) from error
|
||||
|
||||
return JSONResponse(data)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/api/music/spotify/resolve"
|
||||
)
|
||||
async def spotify_resolve(
|
||||
body: dict[str, Any],
|
||||
) -> JSONResponse:
|
||||
query = str(
|
||||
body.get("url")
|
||||
or body.get("query")
|
||||
or ""
|
||||
).strip()
|
||||
|
||||
try:
|
||||
limit = int(
|
||||
body.get("limit")
|
||||
or SPOTDL_MAX_ITEMS
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
limit = SPOTDL_MAX_ITEMS
|
||||
|
||||
try:
|
||||
data = await asyncio.to_thread(
|
||||
_resolve_spotify_sync,
|
||||
query,
|
||||
limit,
|
||||
)
|
||||
|
||||
except ValueError as error:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=str(error),
|
||||
) from error
|
||||
|
||||
except Exception as error:
|
||||
raise HTTPException(
|
||||
status_code=502,
|
||||
detail=(
|
||||
"spotDL resolve failed: "
|
||||
f"{error}"
|
||||
),
|
||||
) from error
|
||||
|
||||
return JSONResponse(
|
||||
data
|
||||
)
|
||||
Reference in New Issue
Block a user