Last active
February 13, 2022 13:48
-
-
Save ander94lakx/63776dacd6e986d935b9f01fff755921 to your computer and use it in GitHub Desktop.
Takes Spotify JSON history and gives the top X listened songs and artists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Spotify Top X Artists and Songs | |
This script takes data from StreamingHistory[x].json files exported from Spotify | |
and gives the most listened songs and artists based on that data | |
Args: | |
top (int): The length of the most listened artists and songs | |
(default is 10) | |
""" | |
from distutils.log import error | |
import json | |
import os | |
import sys | |
def main(): | |
if len(sys.argv) > 1: | |
try: | |
top = int(sys.argv[1]) | |
except ValueError: | |
print('argument must be a positive integer') | |
return | |
else: | |
top = 10 | |
data = [] | |
# Spotify's files default names are StreamingHistory0.json, StreamingHistory1.json, ... | |
for filename in os.listdir(os.getcwd()): | |
if os.path.isfile(filename) and 'StreamingHistory' in filename: | |
print(filename) | |
with open(filename, encoding='utf-8') as file: | |
data += json.load(file) | |
history = {} | |
for song in data: | |
if song['artistName'] in history: | |
if song['trackName'] in history[song['artistName']]: | |
history[song['artistName']][song['trackName']].append(song['endTime']) | |
else: | |
history[song['artistName']][song['trackName']] = [ song['endTime'] ] | |
else: | |
history[song['artistName']] = { song['trackName']: [ song['endTime'] ] } | |
pass | |
songs_play_count = {} | |
artists_play_count = {} | |
for artist in history: | |
artist_count = 0 | |
for song in history[artist]: | |
song_count = len(history[artist][song]) | |
songs_play_count[f'{artist} - {song}'] = song_count | |
artist_count += song_count | |
artists_play_count[artist] = artist_count | |
artists_play_count = sorted(artists_play_count.items(), key=lambda item: item[1], reverse=True) | |
songs_play_count = sorted(songs_play_count.items(), key=lambda item: item[1], reverse=True) | |
top_x_artists = [list(set) for set in artists_play_count[:top]] | |
top_x_songs = [list(set) for set in songs_play_count[:top]] | |
print(f'TOP {top} ARTISTS') | |
for index, value in enumerate(top_x_artists, start=1): | |
print(f'{index} - {value[0]} (x{value[1]})') | |
print(f'TOP {top} SONGS') | |
for index, value in enumerate(top_x_songs, start=1): | |
print(f'{index} - {value[0]} (x{value[1]})') | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment