File size: 1,125 Bytes
dad89e4
 
 
 
 
 
 
 
 
 
 
 
 
 
873436d
dad89e4
 
 
 
 
 
873436d
dad89e4
 
 
 
 
e0bcfa9
dad89e4
 
 
 
 
 
 
e0bcfa9
dad89e4
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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)] +=1 
	return heatmap


def plot(heatmap: np.ndarray):
	fig, ax = plt.subplots()

	ax.imshow(heatmap, cmap="Greens")
	ax.set_title("Recent activity")
	ax.set_yticklabels(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"])
	return fig, ax