Skip to content

Commit

Permalink
Merge branch 'develop' of https://github.com/JeanBaptiste-dlb/Skiptify
Browse files Browse the repository at this point in the history
…into develop
  • Loading branch information
jbdlb committed Oct 23, 2022
2 parents d5daa60 + 456d93a commit e95dd5c
Show file tree
Hide file tree
Showing 4 changed files with 648 additions and 12 deletions.
22 changes: 10 additions & 12 deletions backend/src/app.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
from flask import Flask, redirect, url_for
from backend.src.spotify_api.api_interface import SPOTIFY_API_INTERFACE
import pandas as pd
import numpy as np
from flask_cors import CORS

app = Flask(__name__)
CORS(app)
app.debug = True

sp = SPOTIFY_API_INTERFACE()
Expand All @@ -15,18 +19,12 @@ def index():

@app.route('/current_info')
def current_info():
data = sp.get_current_song()
dict = data.to_dict()
return {'data': dict}, 200 # return data and 200 OK code

@app.route('/skipped_songs')
def skipped_song():
data = sp.get_current_song()
dict = data.to_dict()
return {'data': dict}, 200 # return data and 200 OK code
data = sp.get_metadata_current()
if data is not None:
dict = data.to_dict()
else:
dict = pd.Series()
return dict, 200 # return data and 200 OK code

if __name__ == '__main__':
app.run(debug=True)



58 changes: 58 additions & 0 deletions backend/src/spotify_api/api_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import spotipy.util as util
from pathlib import Path
from datetime import datetime
from sklearn.metrics import pairwise_distances


class SPOTIFY_API_INTERFACE:
Expand Down Expand Up @@ -151,11 +152,68 @@ def get_features(self, track_id) -> pd.Series:
features_results = self.sp.audio_features([track_id])
return pd.Series(features_results[0])

def get_features_to_list(self, track_id):
features_results = self.sp.audio_features([track_id])
json_features = json.dumps(features_results)
features_data = json.loads(json_features)

# Convert features dictionary to a list
features_list = list(features_data[0].values())
return features_list

def get_metadata(self, track_id):
self.sp._update_scope("user-read-currently-playing")
name = self.sp.currently_playing()["item"]["name"]
album_title = self.sp.currently_playing()["item"]["album"][""]
metadata = {"name": name}
return metadata

def calc_dist(self, feature1, feature2):
dss = np.vstack((feature1, feature2))
distance_matrix = pairwise_distances(dss)
return distance_matrix[0][1]

def is_song_skipped(self, track_id):
"""Check if the given is skipped based on distance
Args:
track_id (str): id of the song to check if it should be skipped
Return:
True: skip
False: skip
"""
# self.sp._update_scope("user-read-currently-playing")
# get features of the skipped songs
df_skipped = pd.read_csv('../../../data/player_data/skipped.csv', usecols=[i for i in range(11)])
normalized_d_skipped = (df_skipped - df_skipped.mean()) / (df_skipped.max() - df_skipped.min())

# get features of the non-skipped songs
df_nonskipped = pd.read_csv('../../../data/player_data/non_skipped.csv', usecols=[i for i in range(11)])
normalized_d_nonskipped = (df_nonskipped - df_nonskipped.mean()) / (df_nonskipped.max() - df_nonskipped.min())

# get features of the song to check the similarity distance
feature1 = self.get_features_to_list(track_id)
feature1 = feature1[:11]

# calc distance to the skipped
distances_skipped = []
for i in range(len(normalized_d_skipped)):
feature2 = normalized_d_skipped.iloc[i,:]
dist_tmp = self.calc_dist(feature1, feature2)
distances_skipped.append(dist_tmp)

# calc distance to the skipped
distances_nonskipped = []
for i in range(len(normalized_d_nonskipped)):
feature3 = normalized_d_nonskipped.iloc[i,:]
dist_tmp = self.calc_dist(feature1, feature3)
distances_nonskipped.append(dist_tmp)

# compare distances
dist_skipped = np.array(distances_skipped).mean()
dist_nonskipped = np.array(distances_skipped).mean()
if dist_skipped > dist_nonskipped:
return False
else:
return True
87 changes: 87 additions & 0 deletions notebooks/skiptify_get_currently_song.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import json\n",
"import pandas as pd\n",
"import numpy as np\n",
"\n",
"import spotipy\n",
"\n",
"from sklearn.metrics import pairwise_distances\n",
"from my_token import *"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"scope = 'user-read-currently-playing'\n",
"# scope = 'user-modify-playback-state'\n",
"# scope = 'user-read-recently-played'\n",
"\n",
"# To connect succesfully you need to provide your own Spotify Credentials\n",
"# You can do this signing up in https://developer.spotify.com/ and creating a new app.\n",
"token = spotipy.util.prompt_for_user_token(\n",
" USERNAME, scope, client_id=SPOTIPY_CLIENT_ID, client_secret=SPOTIPY_CLIENT_SECRET, redirect_uri=SPOTIPY_REDIRECT_URI)\n",
"\n",
"sp = spotipy.Spotify(auth=token)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'3c8iiZGfEammKJuWTErE5x'"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# method currently playing return an actual song on Spotify\n",
"current_song = sp.currently_playing()\n",
"current_song['item']['id']"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3.9.13 ('base')",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
},
"orig_nbformat": 4,
"vscode": {
"interpreter": {
"hash": "c6e4e9f98eb68ad3b7c296f83d20e6de614cb42e90992a65aa266555a3137d0d"
}
}
},
"nbformat": 4,
"nbformat_minor": 2
}

0 comments on commit e95dd5c

Please sign in to comment.