Files
vynl/backend/app/api/endpoints/profile.py
root 0ee8f9a144 Add public shareable taste profiles
Users can generate a share link for their taste profile via the
"Share My Taste" button. The link opens a public page showing
listening personality, genre breakdown, audio features, and top
artists with a CTA to register. Token-based URL prevents enumeration.
2026-03-31 20:51:12 -05:00

365 lines
12 KiB
Python

import hashlib
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.config import settings
from app.core.database import get_db
from app.core.security import get_current_user
from app.models.user import User
from app.models.playlist import Playlist
from app.models.track import Track
router = APIRouter(prefix="/profile", tags=["profile"])
def _determine_personality(
genre_count: int,
avg_energy: float,
avg_valence: float,
avg_acousticness: float,
energy_variance: float,
valence_variance: float,
) -> dict:
"""Assign a listening personality based on taste data."""
# High variance in energy/valence = Mood Listener
if energy_variance > 0.06 and valence_variance > 0.06:
return {
"label": "Mood Listener",
"description": "Your music shifts with your emotions. You have playlists for every feeling and aren't afraid to go from euphoric highs to contemplative lows.",
"icon": "drama",
}
# Many different genres = Genre Explorer
if genre_count >= 8:
return {
"label": "Genre Explorer",
"description": "You refuse to be put in a box. Your library is a world tour of sounds, spanning genres most listeners never discover.",
"icon": "globe",
}
# High energy = Energy Seeker
if avg_energy > 0.7:
return {
"label": "Energy Seeker",
"description": "You crave intensity. Whether it's driving beats, soaring guitars, or thundering bass, your music keeps the adrenaline flowing.",
"icon": "zap",
}
# Low energy + high acousticness = Chill Master
if avg_energy < 0.4 and avg_acousticness > 0.5:
return {
"label": "Chill Master",
"description": "You've mastered the art of the vibe. Acoustic textures and mellow grooves define your sonic world — your playlists are a warm blanket.",
"icon": "cloud",
}
# Very consistent taste, low variance = Comfort Listener
if energy_variance < 0.03 and valence_variance < 0.03:
return {
"label": "Comfort Listener",
"description": "You know exactly what you like and you lean into it. Your taste is refined, consistent, and deeply personal.",
"icon": "heart",
}
# Default: Catalog Diver
return {
"label": "Catalog Diver",
"description": "You dig deeper than the singles. Album tracks, B-sides, and deep cuts are your territory — you appreciate the full artistic vision.",
"icon": "layers",
}
@router.get("/taste")
async def get_taste_profile(
user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
"""Aggregate all user playlists/tracks into a full taste profile."""
result = await db.execute(
select(Playlist).where(Playlist.user_id == user.id)
)
playlists = list(result.scalars().all())
all_tracks = []
for p in playlists:
result = await db.execute(select(Track).where(Track.playlist_id == p.id))
all_tracks.extend(result.scalars().all())
if not all_tracks:
return {
"genre_breakdown": [],
"audio_features": {
"energy": 0,
"danceability": 0,
"valence": 0,
"acousticness": 0,
"avg_tempo": 0,
},
"personality": {
"label": "New Listener",
"description": "Import some playlists to discover your listening personality!",
"icon": "music",
},
"top_artists": [],
"track_count": 0,
"playlist_count": len(playlists),
}
# Genre breakdown
genres_count: dict[str, int] = {}
for t in all_tracks:
if t.genres:
for g in t.genres:
genres_count[g] = genres_count.get(g, 0) + 1
total_genre_mentions = sum(genres_count.values()) or 1
top_genres = sorted(genres_count.items(), key=lambda x: x[1], reverse=True)[:10]
genre_breakdown = [
{"name": g, "percentage": round((c / total_genre_mentions) * 100, 1)}
for g, c in top_genres
]
# Audio features averages + variance
energies = []
danceabilities = []
valences = []
acousticnesses = []
tempos = []
for t in all_tracks:
if t.energy is not None:
energies.append(t.energy)
if t.danceability is not None:
danceabilities.append(t.danceability)
if t.valence is not None:
valences.append(t.valence)
if t.acousticness is not None:
acousticnesses.append(t.acousticness)
if t.tempo is not None:
tempos.append(t.tempo)
def avg(lst: list[float]) -> float:
return round(sum(lst) / len(lst), 3) if lst else 0
def variance(lst: list[float]) -> float:
if len(lst) < 2:
return 0
m = sum(lst) / len(lst)
return sum((x - m) ** 2 for x in lst) / len(lst)
avg_energy = avg(energies)
avg_danceability = avg(danceabilities)
avg_valence = avg(valences)
avg_acousticness = avg(acousticnesses)
avg_tempo = round(avg(tempos), 0)
# Personality
personality = _determine_personality(
genre_count=len(genres_count),
avg_energy=avg_energy,
avg_valence=avg_valence,
avg_acousticness=avg_acousticness,
energy_variance=variance(energies),
valence_variance=variance(valences),
)
# Top artists
artist_count: dict[str, int] = {}
for t in all_tracks:
artist_count[t.artist] = artist_count.get(t.artist, 0) + 1
top_artists_sorted = sorted(artist_count.items(), key=lambda x: x[1], reverse=True)[:8]
# Find a representative genre for each top artist
artist_genres: dict[str, str] = {}
for t in all_tracks:
if t.artist in dict(top_artists_sorted) and t.genres and t.artist not in artist_genres:
artist_genres[t.artist] = t.genres[0]
top_artists = [
{
"name": name,
"track_count": count,
"genre": artist_genres.get(name, ""),
}
for name, count in top_artists_sorted
]
return {
"genre_breakdown": genre_breakdown,
"audio_features": {
"energy": round(avg_energy * 100),
"danceability": round(avg_danceability * 100),
"valence": round(avg_valence * 100),
"acousticness": round(avg_acousticness * 100),
"avg_tempo": avg_tempo,
},
"personality": personality,
"top_artists": top_artists,
"track_count": len(all_tracks),
"playlist_count": len(playlists),
}
async def _build_taste_profile(user_id: int, db: AsyncSession) -> dict:
"""Build a taste profile dict for the given user_id (shared logic)."""
result = await db.execute(
select(Playlist).where(Playlist.user_id == user_id)
)
playlists = list(result.scalars().all())
all_tracks = []
for p in playlists:
result = await db.execute(select(Track).where(Track.playlist_id == p.id))
all_tracks.extend(result.scalars().all())
if not all_tracks:
return {
"genre_breakdown": [],
"audio_features": {
"energy": 0,
"danceability": 0,
"valence": 0,
"acousticness": 0,
"avg_tempo": 0,
},
"personality": {
"label": "New Listener",
"description": "Import some playlists to discover your listening personality!",
"icon": "music",
},
"top_artists": [],
"track_count": 0,
"playlist_count": len(playlists),
}
# Genre breakdown
genres_count: dict[str, int] = {}
for t in all_tracks:
if t.genres:
for g in t.genres:
genres_count[g] = genres_count.get(g, 0) + 1
total_genre_mentions = sum(genres_count.values()) or 1
top_genres = sorted(genres_count.items(), key=lambda x: x[1], reverse=True)[:10]
genre_breakdown = [
{"name": g, "percentage": round((c / total_genre_mentions) * 100, 1)}
for g, c in top_genres
]
# Audio features averages + variance
energies = []
danceabilities = []
valences = []
acousticnesses = []
tempos = []
for t in all_tracks:
if t.energy is not None:
energies.append(t.energy)
if t.danceability is not None:
danceabilities.append(t.danceability)
if t.valence is not None:
valences.append(t.valence)
if t.acousticness is not None:
acousticnesses.append(t.acousticness)
if t.tempo is not None:
tempos.append(t.tempo)
def avg(lst: list[float]) -> float:
return round(sum(lst) / len(lst), 3) if lst else 0
def variance(lst: list[float]) -> float:
if len(lst) < 2:
return 0
m = sum(lst) / len(lst)
return sum((x - m) ** 2 for x in lst) / len(lst)
avg_energy = avg(energies)
avg_danceability = avg(danceabilities)
avg_valence = avg(valences)
avg_acousticness = avg(acousticnesses)
avg_tempo = round(avg(tempos), 0)
# Personality
personality = _determine_personality(
genre_count=len(genres_count),
avg_energy=avg_energy,
avg_valence=avg_valence,
avg_acousticness=avg_acousticness,
energy_variance=variance(energies),
valence_variance=variance(valences),
)
# Top artists
artist_count: dict[str, int] = {}
for t in all_tracks:
artist_count[t.artist] = artist_count.get(t.artist, 0) + 1
top_artists_sorted = sorted(artist_count.items(), key=lambda x: x[1], reverse=True)[:8]
artist_genres: dict[str, str] = {}
for t in all_tracks:
if t.artist in dict(top_artists_sorted) and t.genres and t.artist not in artist_genres:
artist_genres[t.artist] = t.genres[0]
top_artists = [
{
"name": name,
"track_count": count,
"genre": artist_genres.get(name, ""),
}
for name, count in top_artists_sorted
]
return {
"genre_breakdown": genre_breakdown,
"audio_features": {
"energy": round(avg_energy * 100),
"danceability": round(avg_danceability * 100),
"valence": round(avg_valence * 100),
"acousticness": round(avg_acousticness * 100),
"avg_tempo": avg_tempo,
},
"personality": personality,
"top_artists": top_artists,
"track_count": len(all_tracks),
"playlist_count": len(playlists),
}
def _generate_profile_token(user_id: int) -> str:
"""Generate a deterministic share token for a user's profile."""
return hashlib.sha256(
f"profile:{user_id}:{settings.SECRET_KEY}".encode()
).hexdigest()[:16]
@router.get("/share-link")
async def get_profile_share_link(user: User = Depends(get_current_user)):
"""Generate a share link for the user's taste profile."""
token = _generate_profile_token(user.id)
return {"share_url": f"{settings.FRONTEND_URL}/taste/{user.id}/{token}"}
@router.get("/public/{user_id}/{token}")
async def get_public_profile(
user_id: int,
token: str,
db: AsyncSession = Depends(get_db),
):
"""Public taste profile — no auth required."""
expected = _generate_profile_token(user_id)
if token != expected:
raise HTTPException(status_code=404, detail="Invalid profile link")
result = await db.execute(select(User).where(User.id == user_id))
user = result.scalar_one_or_none()
if not user:
raise HTTPException(status_code=404, detail="Profile not found")
profile = await _build_taste_profile(user_id, db)
profile["name"] = user.name.split()[0] # First name only for privacy
return profile