CoolFace
Apppublic

trhacknon/Spotify

sourceHugging Faceupdated 3y agoView on Hugging Face
0likes
heatmap.py39 linesDownload Raw Back to root
1from datetime import datetime2from typing import List3import numpy as np4from spotipy import Spotify5from dateutil.parser import parse6import matplotlib.pyplot as plt7 8def fetch_recent_songs(client: Spotify):9	cursor = client.current_user_recently_played()10	recently_played: List[dict] = cursor["items"]11 12	max_iterations = 3013	it = 014	while it < max_iterations and cursor["cursors"] is not None:15		cursor = client.current_user_recently_played(before=cursor["cursors"]["before"])16		recently_played.extend(cursor["items"])17 18	return recently_played19 20def build_heatmap(recent_songs: List[dict]) -> np.ndarray:21	heatmap = np.zeros((7, 20))22	now = datetime.now().astimezone()23 24	for track in recent_songs:25		played_at = parse(track["played_at"])26		weekday = datetime.weekday(played_at)27		week_offset = (now - played_at).days // 728		heatmap[weekday, -(week_offset +1)] +=1 29	return heatmap30 31 32def plot(heatmap: np.ndarray):33	fig, ax = plt.subplots()34 35	ax.imshow(heatmap, cmap="Greens")36	ax.set_ylim(0, 6)37	ax.set_title("Recent activity")38	ax.set_yticklabels(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"])39	return fig, ax