Adds the per-kind generator modules and registers them with the
PlaylistKindRegistry so the manager's `refresh_playlist` can dispatch
to any of them.
Generators (each in its own module under
`core/personalized/generators/`):
Singletons (variant=''):
- hidden_gems -> wraps service.get_hidden_gems
- discovery_shuffle -> wraps service.get_discovery_shuffle
- popular_picks -> wraps service.get_popular_picks
Variant-bearing kinds:
- time_machine -> variant = decade label ('1980s', '1990s', ...).
Variant resolver returns 7 standard decades.
Generator parses '1980s' -> 1980 + delegates
to service.get_decade_playlist.
- genre_playlist -> variant = URL-safe genre key
('electronic_dance', 'hip_hop_rap', ...).
Resolver normalizes parent-genre keys from
service.GENRE_MAPPING; free-form keywords
pass through to service.get_genre_playlist.
- daily_mix -> variant = top-genre rank ('1' / '2' / '3' / '4').
Generator looks up user's Nth-ranked library
genre and returns discovery picks within it.
Library half (was a stub returning []) is
intentionally dropped: tracks table has no
source IDs, so library rows can't sync. Fixed
the stub to return [] cleanly without the
misleading log warning.
- fresh_tape -> Spotify Release Radar. Reads curated track
IDs from discovery_curated_playlists (tries
'release_radar_<source>' first, falls back to
'release_radar') and hydrates against the
discovery pool.
- archives -> Spotify Discover Weekly. Same hydration path
as fresh_tape but uses 'discovery_weekly'.
- seasonal_mix -> variant = season key ('halloween' / 'christmas'
/ 'valentines' / 'summer' / 'spring' / 'autumn').
Reads curated IDs via SeasonalDiscoveryService
then hydrates from seasonal_tracks (which
carries full track_data_json).
Each module:
- Defines `generate(deps, variant, config) -> List[Track]`.
- Defines `SPEC = PlaylistKindSpec(...)` and registers it on import
(idempotent — re-import safe via `if registry.get(...) is None`).
- For variant-bearing kinds, also defines `variant_resolver(deps)`.
Shared helpers in `_common.py`:
- `get_service(deps)` pulls the legacy
`PersonalizedPlaylistsService` instance (deps.service or
deps['service']).
- `coerce_tracks(rows)` runs each dict through `Track.from_dict`,
tolerates None / non-list inputs.
Tests (50 new, total 85 across personalized subsystem):
- Singletons: registration + display name + dispatch + limit
forwarding + empty/None tolerance + missing-deps error +
dict-form deps acceptance (16 tests).
- Variants: variant_resolver listing + label parsing + invalid
variant errors + parent-key normalization + free-form passthrough
(13 tests).
- Curated/hybrid: daily_mix rank-to-genre resolution + rank-out-of-
range empty + invalid-variant error; fresh_tape & archives
hydration order + missing-id skip + source-specific-then-fallback
key dispatch + limit + missing-database-dep error; seasonal_mix
curated-id hydration order + missing-id skip + JSON round-trip +
empty-curated empty + limit + missing-service error (21 tests).
3304+ tests pass. No regression on existing 62 personalized tests.
119 lines
4.6 KiB
Python
119 lines
4.6 KiB
Python
"""Fresh Tape (Spotify Release Radar) generator.
|
|
|
|
Reads the curated track-id list cached in ``discovery_curated_playlists``
|
|
under ``release_radar_<source>`` (with fallback to ``release_radar``)
|
|
and hydrates each ID against the discovery pool to produce full Track
|
|
records. The Spotify enrichment worker is responsible for keeping the
|
|
curated list fresh — this generator is just a read-and-hydrate path."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from typing import Any, List
|
|
|
|
from core.personalized.generators._common import coerce_tracks
|
|
from core.personalized.specs import PlaylistKindSpec, get_registry
|
|
from core.personalized.types import PlaylistConfig, Track
|
|
|
|
|
|
KIND = 'fresh_tape'
|
|
|
|
|
|
def _hydrate_curated(deps: Any, curated_type_prefix: str, config: PlaylistConfig) -> List[Track]:
|
|
"""Shared body for Fresh Tape + Archives — pulls the cached IDs
|
|
from discovery_curated_playlists and hydrates them via the live
|
|
discovery pool. Returns a Track list trimmed to ``config.limit``."""
|
|
# Allow tests to inject a fake db / service; production flow gets
|
|
# them from the manager's deps.
|
|
db = getattr(deps, 'database', None) or (deps.get('database') if isinstance(deps, dict) else None)
|
|
if db is None:
|
|
raise RuntimeError("Curated-playlist generator deps missing `database`")
|
|
|
|
profile_id = _resolve_profile_id(deps)
|
|
active_source = _resolve_active_source(deps)
|
|
|
|
# Try source-specific then generic, mirrors web_server endpoint behavior.
|
|
curated_ids = (
|
|
db.get_curated_playlist(f'{curated_type_prefix}_{active_source}', profile_id=profile_id)
|
|
or db.get_curated_playlist(curated_type_prefix, profile_id=profile_id)
|
|
or []
|
|
)
|
|
if not curated_ids:
|
|
return []
|
|
|
|
pool_rows = db.get_discovery_pool_tracks(
|
|
limit=5000, new_releases_only=False,
|
|
source=active_source, profile_id=profile_id,
|
|
)
|
|
by_id = {}
|
|
for t in pool_rows:
|
|
if active_source == 'spotify' and getattr(t, 'spotify_track_id', None):
|
|
by_id[t.spotify_track_id] = t
|
|
elif active_source == 'deezer' and getattr(t, 'deezer_track_id', None):
|
|
by_id[t.deezer_track_id] = t
|
|
elif active_source == 'itunes' and getattr(t, 'itunes_track_id', None):
|
|
by_id[t.itunes_track_id] = t
|
|
|
|
tracks: List[Track] = []
|
|
for tid in curated_ids:
|
|
candidate = by_id.get(tid)
|
|
if candidate is None:
|
|
continue
|
|
# The pool track is a row-like object; coerce to dict for
|
|
# Track.from_dict's existing tolerance.
|
|
td = getattr(candidate, 'track_data_json', None)
|
|
if isinstance(td, str):
|
|
try:
|
|
td = json.loads(td)
|
|
except (ValueError, TypeError):
|
|
td = None
|
|
track_dict = {
|
|
'spotify_track_id': getattr(candidate, 'spotify_track_id', None),
|
|
'itunes_track_id': getattr(candidate, 'itunes_track_id', None),
|
|
'deezer_track_id': getattr(candidate, 'deezer_track_id', None),
|
|
'track_name': getattr(candidate, 'track_name', ''),
|
|
'artist_name': getattr(candidate, 'artist_name', ''),
|
|
'album_name': getattr(candidate, 'album_name', ''),
|
|
'album_cover_url': getattr(candidate, 'album_cover_url', None),
|
|
'duration_ms': getattr(candidate, 'duration_ms', 0),
|
|
'popularity': getattr(candidate, 'popularity', 0),
|
|
'track_data_json': td,
|
|
'source': getattr(candidate, 'source', active_source),
|
|
}
|
|
tracks.append(Track.from_dict(track_dict))
|
|
if len(tracks) >= config.limit:
|
|
break
|
|
return tracks
|
|
|
|
|
|
def _resolve_profile_id(deps: Any) -> int:
|
|
fn = getattr(deps, 'get_current_profile_id', None) or (
|
|
deps.get('get_current_profile_id') if isinstance(deps, dict) else None
|
|
)
|
|
return fn() if callable(fn) else 1
|
|
|
|
|
|
def _resolve_active_source(deps: Any) -> str:
|
|
fn = getattr(deps, 'get_active_discovery_source', None) or (
|
|
deps.get('get_active_discovery_source') if isinstance(deps, dict) else None
|
|
)
|
|
return fn() if callable(fn) else 'spotify'
|
|
|
|
|
|
def generate(deps: Any, variant: str, config: PlaylistConfig) -> List[Track]:
|
|
return _hydrate_curated(deps, 'release_radar', config)
|
|
|
|
|
|
SPEC = PlaylistKindSpec(
|
|
kind=KIND,
|
|
name_template='Fresh Tape',
|
|
description='Your Spotify Release Radar — new releases from artists you follow.',
|
|
default_config=PlaylistConfig(limit=50, max_per_album=5, max_per_artist=10),
|
|
generator=generate,
|
|
requires_variant=False,
|
|
tags=['curated', 'spotify'],
|
|
)
|
|
|
|
|
|
if get_registry().get(KIND) is None:
|
|
get_registry().register(SPEC)
|