Export to PNG (#1)

This commit is contained in:
Mylloon 2023-09-06 16:21:25 +02:00
parent be7a7b6768
commit d5545fb699
Signed by: Anri
GPG key ID: A82D63DFF8D1317F
4 changed files with 109 additions and 62 deletions

4
.gitignore vendored
View file

@ -2,6 +2,8 @@
/lib
pyvenv.cfg
/.vscode
.env
.cache
*.csv
*.png

View file

@ -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.

107
main.py
View file

@ -1,24 +1,29 @@
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from matplotlib import pyplot as plt
from dotenv import load_dotenv
from spotipy import Spotify, exceptions
from spotipy.oauth2 import SpotifyOAuth
# 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
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 = spotify.current_user_saved_tracks(limit=limit, offset=offset)
except spotipy.exceptions.SpotifyException as e:
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
@ -29,24 +34,74 @@ while True:
offset += limit
# Break the loop if we reach the end
if len(results['items']) == 0:
if len(results["items"]) == 0:
break
saved_tracks.extend(results['items'])
saved_tracks.extend(results["items"])
return saved_tracks
with open("result.csv", "w") as file:
file.write("titre;artiste;date\n")
def get_years(data: list) -> list:
"""Extract data"""
years = []
for item in data:
track = item["track"]
years.append(int(track['album']['release_date'][:4]))
# Extract data
buffer = ""
for item in saved_tracks:
track = item['track']
return years
buffer += f"{track['name'].replace(';', ',')};"
buffer += f"{track['artists'][0]['name'].replace(';', ',')};"
buffer += f"{track['album']['release_date']}\n"
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
# Save to a file
with open("result.csv", "a") as file:
file.write(buffer)
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}")

View file

@ -1,2 +1,3 @@
python-dotenv==1.0.0
spotipy==2.23.0
matplotlib==3.7.2