Spotify / heatmap.py
sbrandeis's picture
sbrandeis HF staff
heatmap (#1)
dad89e4
raw history blame
No virus
1.06 kB
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 = 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()
for track in recent_songs:
played_at = parse(track["played_at"])
weekday = datetime.weekday(played_at)
week_offset = (now - played_at).days // 7
print(weekday, week_offset)
heatmap[weekday, -week_offset]
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