In the previous lesson, you explored how the dashboard interacts with your backend — browsing tracks, logging listens, and viewing recommendations. Now, we shift to a new backend feature: the listening trends API.
- For users: Trends provide quick insights into their listening habits (mood, tempo, energy).
- For the smart system: Trends are key for session-aware recommendations, as they help the model adapt to current user preferences.
In this unit, we’ll add a new endpoint, /api/trends/<user_id>, and implement trend analysis in a new session_analysis.py module.
The heavy lifting is done by the get_recent_session_trends function in src/session_analysis.py. Its job is to look at a user’s last N sessions (default 5) and extract three key statistics:
- Most common mood – The mood that appears most frequently in recent tracks.
- Average tempo – The mean tempo of those tracks.
- Average energy – The mean energy value (on a 0–1 scale) for the same set.
Code Breakdown
What’s happening here?
- It reads
sessions.csvto get all listening events. - Filters only the sessions for the given
user_id. - Sorts them by time and picks the most recent N sessions.
- Retrieves each track’s mood, tempo, and energy via
get_track_by_id. - Calculates the most common mood and averages for tempo and energy.
- Returns a dictionary like:
The function is exposed to the frontend through this new route in app.py:
Key points:
- When a
GETrequest hits/api/trends/<user_id>, it fetches trend data for that user. - If no sessions are found, it returns an empty
trendsobject with a message. - If something goes wrong, it safely returns a 500 error.
Example Request:
GET /api/trends/user123
Example Response:
In this lesson, you learned how the Music Player analyzes your recent listening sessions to find trends. You saw how the app collects session data, how the get_recent_session_trends function works, and how the /api/trends/<user_id> endpoint provides this information.
Next, we’ll move toward session-aware recommendations, where these trend metrics will influence which tracks are suggested to the user.
