from datetime import datetime from typing import List import numpy as np from spotipy import Spotify from dateutil.parser import parse import matplotlib.pyplot as plt def fetch_recent_songs(client: Spotify): cursor = client.current_user_recently_played() recently_played: List[dict] = cursor["items"] max_iterations = 30 it = 0 while it < max_iterations and cursor["cursors"] is not None: cursor = client.current_user_recently_played(before=cursor["cursors"]["before"]) recently_played.extend(cursor["items"]) return recently_played def build_heatmap(recent_songs: List[dict]) -> np.ndarray: heatmap = np.zeros((7, 20)) now = datetime.now().astimezone() for track in recent_songs: played_at = parse(track["played_at"]) weekday = datetime.weekday(played_at) week_offset = (now - played_at).days // 7 heatmap[weekday, -week_offset] +=1 return heatmap def plot(heatmap: np.ndarray): fig, ax = plt.subplots() ax.imshow(heatmap, cmap="Greens") ax.set_yticklabels(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]) return fig, ax