This repository has been archived on 2023-09-06. You can view files and clone it, but cannot push or open issues or pull requests.
generatio/main.py
2023-09-06 16:21:25 +02:00

107 lines
2.8 KiB
Python

from matplotlib import pyplot as plt
from dotenv import load_dotenv
from spotipy import Spotify, exceptions
from spotipy.oauth2 import SpotifyOAuth
def get_user_tracks(spotify: Spotify) -> list:
"""Fetch the saved tracks of a specified user."""
offset = 0
saved_tracks = []
limit = 50
# Loop until either we reach the end of the playlist, or we getting limited
# by the API
while True:
try:
print(f"Récupération {offset}-{offset + limit}")
results: dict | None = spotify.current_user_saved_tracks(
limit=limit,
offset=offset
)
if results is None:
print("L'API de Spotify délire")
exit(1)
except exceptions.SpotifyException as e:
if e.http_status == 429:
print("Récolte terminé, l'API a bien mangé.")
break
else:
print(f"Ca a buggé: {e}")
exit(1)
else:
offset += limit
# Break the loop if we reach the end
if len(results["items"]) == 0:
break
saved_tracks.extend(results["items"])
return saved_tracks
def get_years(data: list) -> list:
"""Extract data"""
years = []
for item in data:
track = item["track"]
years.append(int(track['album']['release_date'][:4]))
return years
def get_occurences(years: list) -> dict:
"""
Map of all the years and how many times there is an occurence,
sorted by years
"""
year_count = {}
for year in years:
if year in year_count:
year_count[year] += 1
else:
if year > 0:
year_count[year] = 1
return dict(sorted(year_count.items()))
def export_data(color) -> str:
"""Build a graphic"""
plt.clf()
match color:
case "light":
pass
case "dark":
plt.style.use("dark_background")
case _:
print("Comprends pas cette couleur")
exit(1)
filename = f"resultat_{color}.png"
plt.plot(occurences.keys(), occurences.values())
plt.title("Occurrences of what I've listened to over the years")
plt.xlabel("Year")
plt.ylabel("Occurrence")
plt.savefig(filename)
return filename
if __name__ == '__main__':
# Load .env
load_dotenv()
# Connect to spotify
spotify = Spotify(
auth_manager=SpotifyOAuth(scope="user-library-read", open_browser=False)
)
# Get of release year of liked user tracks
saved_tracks = get_user_tracks(spotify)
years = get_years(saved_tracks)
# Get how many time each years appears in the data
occurences = get_occurences(years)
# Build chart
light, dark = export_data("light"), export_data("dark")
print(f"Check ton graph:\n- {light}\n- {dark}")