Export to PNG (#1)
This commit is contained in:
parent
be7a7b6768
commit
d5545fb699
4 changed files with 109 additions and 62 deletions
4
.gitignore
vendored
4
.gitignore
vendored
|
@ -2,6 +2,8 @@
|
||||||
/lib
|
/lib
|
||||||
pyvenv.cfg
|
pyvenv.cfg
|
||||||
|
|
||||||
|
/.vscode
|
||||||
|
|
||||||
.env
|
.env
|
||||||
.cache
|
.cache
|
||||||
*.csv
|
*.png
|
||||||
|
|
19
README.md
19
README.md
|
@ -1,4 +1,4 @@
|
||||||
# GeneRatio
|
# [GeneRatio](https://twitter.com/Mylloon/status/1699226564519514358)
|
||||||
|
|
||||||
- Installe les dépendances : `pip install -r requirements.txt`
|
- Installe les dépendances : `pip install -r requirements.txt`
|
||||||
- Remplir un .env avec les champs suivant :
|
- Remplir un .env avec les champs suivant :
|
||||||
|
@ -9,18 +9,7 @@ SPOTIPY_CLIENT_SECRET="XXXXX"
|
||||||
SPOTIPY_REDIRECT_URI="http://127.0.0.1:9090"
|
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,
|
Suis les étapes du script, à la fin, il devrait y avoir un resultat.png.
|
||||||
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)
|
|
||||||
|
|
113
main.py
113
main.py
|
@ -1,24 +1,29 @@
|
||||||
import spotipy
|
from matplotlib import pyplot as plt
|
||||||
from spotipy.oauth2 import SpotifyOAuth
|
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
|
from spotipy import Spotify, exceptions
|
||||||
|
from spotipy.oauth2 import SpotifyOAuth
|
||||||
|
|
||||||
# Load .env
|
|
||||||
load_dotenv()
|
|
||||||
|
|
||||||
# Connect to spotify
|
def get_user_tracks(spotify: Spotify) -> list:
|
||||||
spotify = spotipy.Spotify(auth_manager=SpotifyOAuth(
|
"""Fetch the saved tracks of a specified user."""
|
||||||
scope="user-library-read",
|
offset = 0
|
||||||
open_browser=False))
|
saved_tracks = []
|
||||||
|
limit = 50
|
||||||
|
|
||||||
# Fetch the saved tracks of a specified user
|
# Loop until either we reach the end of the playlist, or we getting limited
|
||||||
offset = 0
|
# by the API
|
||||||
saved_tracks = []
|
while True:
|
||||||
limit = 50
|
|
||||||
while True:
|
|
||||||
try:
|
try:
|
||||||
print(f"Récupération {offset}-{offset + limit}")
|
print(f"Récupération {offset}-{offset + limit}")
|
||||||
results = spotify.current_user_saved_tracks(limit=limit, offset=offset)
|
results: dict | None = spotify.current_user_saved_tracks(
|
||||||
except spotipy.exceptions.SpotifyException as e:
|
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:
|
if e.http_status == 429:
|
||||||
print("Récolte terminé, l'API a bien mangé.")
|
print("Récolte terminé, l'API a bien mangé.")
|
||||||
break
|
break
|
||||||
|
@ -29,24 +34,74 @@ while True:
|
||||||
offset += limit
|
offset += limit
|
||||||
|
|
||||||
# Break the loop if we reach the end
|
# Break the loop if we reach the end
|
||||||
if len(results['items']) == 0:
|
if len(results["items"]) == 0:
|
||||||
break
|
break
|
||||||
|
|
||||||
saved_tracks.extend(results['items'])
|
saved_tracks.extend(results["items"])
|
||||||
|
|
||||||
|
return saved_tracks
|
||||||
|
|
||||||
with open("result.csv", "w") as file:
|
def get_years(data: list) -> list:
|
||||||
file.write("titre;artiste;date\n")
|
"""Extract data"""
|
||||||
|
years = []
|
||||||
|
for item in data:
|
||||||
|
track = item["track"]
|
||||||
|
years.append(int(track['album']['release_date'][:4]))
|
||||||
|
|
||||||
# Extract data
|
return years
|
||||||
buffer = ""
|
|
||||||
for item in saved_tracks:
|
|
||||||
track = item['track']
|
|
||||||
|
|
||||||
buffer += f"{track['name'].replace(';', ',')};"
|
def get_occurences(years: list) -> dict:
|
||||||
buffer += f"{track['artists'][0]['name'].replace(';', ',')};"
|
"""
|
||||||
buffer += f"{track['album']['release_date']}\n"
|
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
|
return dict(sorted(year_count.items()))
|
||||||
with open("result.csv", "a") as file:
|
|
||||||
file.write(buffer)
|
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}")
|
||||||
|
|
|
@ -1,2 +1,3 @@
|
||||||
python-dotenv==1.0.0
|
python-dotenv==1.0.0
|
||||||
spotipy==2.23.0
|
spotipy==2.23.0
|
||||||
|
matplotlib==3.7.2
|
||||||
|
|
Reference in a new issue