From d5545fb699239d74a039c517bbf0617dff8b2e69 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 6 Sep 2023 16:21:25 +0200 Subject: [PATCH] Export to PNG (#1) --- .gitignore | 4 +- README.md | 19 ++---- main.py | 147 ++++++++++++++++++++++++++++++++--------------- requirements.txt | 1 + 4 files changed, 109 insertions(+), 62 deletions(-) diff --git a/.gitignore b/.gitignore index d6ddb70..dec832d 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,8 @@ /lib pyvenv.cfg +/.vscode + .env .cache -*.csv +*.png diff --git a/README.md b/README.md index cc4392c..5172283 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# GeneRatio +# [GeneRatio](https://twitter.com/Mylloon/status/1699226564519514358) - Installe les dépendances : `pip install -r requirements.txt` - Remplir un .env avec les champs suivant : @@ -9,18 +9,7 @@ SPOTIPY_CLIENT_SECRET="XXXXX" SPOTIPY_REDIRECT_URI="http://127.0.0.1:9090" ``` -Les données devraient correspondre avec tes infos persos de Spotify Dashboard +> Les données devraient correspondre avec tes infos persos +> de [Spotify Dashboard](https://developer.spotify.com/dashboard) -Le script va probablement te demander d'ouvrir un lien, il faudra cliquer dessus, -attendre, et envoyer l'URL final dans le script au final (me DM si c'est pas claire) - ---- - -Quand le script est fini, faut ouvrir google sheets, - -Colonne D: `=DATEVAL(C2)` (donne un chiffre chelou, étendre tout du long) -Colonne E: `=ANNEE(D2)` (donne l'année correspondant a la musique, étendre tout du long) -Colonne F: Faire une liste des années (pour le graphique final) -Colonne G: `=NB.SI(E:E;F2)` (donne le nombre d'occurence, étendre jusqu'a la fin de la colonne F) - -[Faire un graphique dans l'interface de Google](https://twitter.com/Mylloon/status/1699226564519514358) +Suis les étapes du script, à la fin, il devrait y avoir un resultat.png. diff --git a/main.py b/main.py index 3598f4f..3e58b62 100644 --- a/main.py +++ b/main.py @@ -1,52 +1,107 @@ -import spotipy -from spotipy.oauth2 import SpotifyOAuth +from matplotlib import pyplot as plt from dotenv import load_dotenv - -# Load .env -load_dotenv() - -# Connect to spotify -spotify = spotipy.Spotify(auth_manager=SpotifyOAuth( - scope="user-library-read", - open_browser=False)) - -# Fetch the saved tracks of a specified user -offset = 0 -saved_tracks = [] -limit = 50 -while True: - try: - print(f"Récupération {offset}-{offset + limit}") - results = spotify.current_user_saved_tracks(limit=limit, offset=offset) - except spotipy.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']) +from spotipy import Spotify, exceptions +from spotipy.oauth2 import SpotifyOAuth -with open("result.csv", "w") as file: - file.write("titre;artiste;date\n") +def get_user_tracks(spotify: Spotify) -> list: + """Fetch the saved tracks of a specified user.""" + offset = 0 + saved_tracks = [] + limit = 50 -# Extract data -buffer = "" -for item in saved_tracks: - track = item['track'] + # 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 + ) - buffer += f"{track['name'].replace(';', ',')};" - buffer += f"{track['artists'][0]['name'].replace(';', ',')};" - buffer += f"{track['album']['release_date']}\n" + 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 -# Save to a file -with open("result.csv", "a") as file: - file.write(buffer) + # 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}") diff --git a/requirements.txt b/requirements.txt index b51407c..c0596d1 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,3 @@ python-dotenv==1.0.0 spotipy==2.23.0 +matplotlib==3.7.2