Skip to content

Commit

Permalink
changes for song_features save with id
Browse files Browse the repository at this point in the history
  • Loading branch information
jbdlb committed Oct 22, 2022
1 parent 11b4f16 commit 1258f70
Show file tree
Hide file tree
Showing 17 changed files with 164 additions and 73 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
.cache*
settings.json

data/tmp
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
Expand Down
30 changes: 30 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"cwd": "${workspaceFolder}",
"env": {
"ENV_FILE": ".env",
"PYTHONPATH": "${cwd}",
"VERBOSITY": "DEBUG",
}
},
{
"name": "Main File",
"type": "python",
"request": "launch",
"program": "app/main.py",
"console": "integratedTerminal",
"cwd": "${workspaceFolder}",
"env": {
"PYTHONPATH": "${cwd}",
"VERBOSITY": "DEBUG"
}
}
]
}
Empty file added backend/__init__.py
Empty file.
Empty file added backend/src/__init__.py
Empty file.
18 changes: 14 additions & 4 deletions backend/src/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class Settings(BaseSettings):

# Application Path
APP_PATH: str = os.path.abspath(".")
DATA_PATH: str = os.path.join(APP_PATH, "app", "data")
DATA_PATH: str = os.path.join(APP_PATH, "data")

# -----------------
# Token for getting song's info from Spotify
Expand All @@ -44,12 +44,20 @@ class Settings(BaseSettings):
token = ""
# -----------------

scope = 'user-read-currently-playing'
scope = "user-read-currently-playing"

# To connect succesfully you need to provide your own Spotify Credentials
# You can do this signing up in https://developer.spotify.com/ and creating a new app.
token = spotipy.util.prompt_for_user_token(
USERNAME, scope, client_id=SPOTIPY_CLIENT_ID, client_secret=SPOTIPY_CLIENT_SECRET, redirect_uri=SPOTIPY_REDIRECT_URI)
TOKEN: Any = None

def set_token(self, scope):
self.TOKEN = spotipy.util.prompt_for_user_token(
self.USERNAME,
scope,
client_id=self.SPOTIPY_CLIENT_ID,
client_secret=self.SPOTIPY_CLIENT_SECRET,
redirect_uri=self.SPOTIPY_REDIRECT_URI,
)


def env_load(env_file: str) -> Settings:
Expand All @@ -75,6 +83,8 @@ def env_load(env_file: str) -> Settings:
except Exception as message:
print(f"Error: impossible to read the env: {message}")
return None


# cache system to read the settings without everytime read the .env file


Expand Down
Empty file added backend/src/db/__init__.py
Empty file.
Empty file added backend/src/model/__init__.py
Empty file.
3 changes: 2 additions & 1 deletion backend/src/model/decision_template.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from backend.src.config import settings


def decide(current_song, history) -> bool:
"""
Returns if the song
Args:
current_song (_type_): _description_
history (_type_): _description_
"""
"""
Empty file.
127 changes: 73 additions & 54 deletions backend/src/spotify_api/api_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,79 +7,98 @@
import numpy as np
from pathlib import Path


class SPOTIFY_API_INTERFACE:
def __init__(self) -> None:
self.scope = settings.scope
self.token = spotipy.util.prompt_for_user_token(
settings.USERNAME, settings.scope, client_id=settings.SPOTIPY_CLIENT_ID, client_secret=settings.SPOTIPY_CLIENT_SECRET,
redirect_uri=settings.SPOTIPY_REDIRECT_URI)
self.sp = spotipy.Spotify(auth=self.token)
self.skiped=pd.DataFrame()
self.played_emtirely=pd.DataFrame()
self.skiped = pd.DataFrame()
self.played_emtirely = pd.DataFrame()
self.token = None
self.sp = None
self._update_scope(settings.scope)

def _update_scope(self, scope:str):
self.token = spotipy.util.prompt_for_user_token(
settings.USERNAME, settings.scope, client_id=settings.SPOTIPY_CLIENT_ID, client_secret=settings.SPOTIPY_CLIENT_SECRET,
redirect_uri=settings.SPOTIPY_REDIRECT_URI)
self.sp=spotipy.Spotify(auth=self.token)
def _update_scope(self, scope: str):
settings.set_token(scope)
self.sp = spotipy.Spotify(auth=settings.TOKEN)
return None


def get_song_history(self):
self._update_scope()
self._update_scope("user-read-recently-played")
names = []
songs = []
song_ids = []
list_of_all = []
df = pd.DataFrame(list_of_all, columns=["danceability",
"energy",
"key",
"loudness",
"mode",
"speechiness",
"acousticness",
"instrumentalness",
"liveness",
"valence",
"tempo",
"type",
"id",
"uri",
"track_href",
"analysis_url",
"duration_ms",
"time_signature"])
history = self.sp.current_user_recently_played(limit=50, after=None, before=None)
for i in range(50):
song_id = history['items'][i]['track']['id']
df = pd.DataFrame(
list_of_all,
columns=[
"danceability",
"energy",
"key",
"loudness",
"mode",
"speechiness",
"acousticness",
"instrumentalness",
"liveness",
"valence",
"tempo",
"type",
"id",
"uri",
"track_href",
"analysis_url",
"duration_ms",
"time_signature",
],
)
history = self.sp.current_user_recently_played(
limit=50, after=None, before=None
)
history_size=len(history["items"])
for i in range(history_size):
song_id = history["items"][i]["track"]["id"]
song_ids.append(song_id)
for i in range(50):
names.append(history['items'][i]['track']['album']['artists'][0]['name'])
songs.append(history['items'][i]['track']['name'])
for i in range(50):
list_of_all.appends(self.get_features(song_ids[i]))
df['names'] = names
df['song'] = songs
df.drop(['type','uri','id', "track_href","analysis_url","duration_ms", "time_signature"], axis=1)
names.append(history["items"][i]["track"]["album"]["artists"][0]["name"])
songs.append(history["items"][i]["track"]["name"])
list_of_all.append(self.get_features(song_id))
df["names"] = names
df["song"] = songs
df.drop(
[
"type",
"uri",
"id",
"track_href",
"analysis_url",
"duration_ms",
"time_signature",
],
axis=1,
)
return df

def get_current_song(self):
self._update_scope(scope = 'user-read-currently-playing')
self._update_scope(scope="user-read-currently-playing")
current_song = self.sp.currently_playing()
id_=current_song['item']['id']
id_ = current_song["item"]["id"]
return self.get_features(id_)

def get_next_song(self) -> pd.Series:
return None
return None

def get_playlist_id(self):
self._update_scope(scope="user-read-currently-playing")
current_song = self.sp.currently_playing()
return current_song["context"]["uri"].split(":")[-1]

def get_features(self, track_id) -> pd.Series:
features_results = self.sp.audio_features([track_id])
json_features = json.dumps(features_results, Path(settings.DATA_PATH, "tmp", "song_feature.json"))
features_data = json.loads(json_features)
features_results = self.sp.audio_features([track_id])
save_path= Path(settings.DATA_PATH, "tmp", "song_features")
save_path.mkdir(parents=True, exist_ok=True)
with open(Path(settings.DATA_PATH, "tmp", "song_features", f"{track_id}.json"), "w") as writer:
json_features = json.dump(
features_results, writer
)
features_data = json.load(open(Path(settings.DATA_PATH, "tmp", "song_features", f"{track_id}.json"), "r"))
# Convert features dictionary to a list
features_list = list(features_data[0].values())
return pd.Series(features_list)




return pd.Series(features_data[0])
11 changes: 8 additions & 3 deletions backend/src/spotify_api/frontend_info.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import spotipy

# -----------------
# Token for getting song's info from Spotify
USERNAME = "nellen.noemi"
Expand All @@ -10,13 +11,17 @@
token = ""
# -----------------

scope = 'user-read-currently-playing'
scope = "user-read-currently-playing"

# To connect succesfully you need to provide your own Spotify Credentials
# You can do this signing up in https://developer.spotify.com/ and creating a new app.
token = spotipy.util.prompt_for_user_token(
USERNAME, scope, client_id=SPOTIPY_CLIENT_ID, client_secret=SPOTIPY_CLIENT_SECRET,
redirect_uri=SPOTIPY_REDIRECT_URI)
USERNAME,
scope,
client_id=SPOTIPY_CLIENT_ID,
client_secret=SPOTIPY_CLIENT_SECRET,
redirect_uri=SPOTIPY_REDIRECT_URI,
)

sp = spotipy.Spotify(auth=token)
current_song = sp.currently_playing()
25 changes: 21 additions & 4 deletions backend/src/spotify_api/spotify_actioner.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,25 @@ class SpotifyActionnner:
def __init__(self):
self.scope = settings.scope
self.token = spotipy.util.prompt_for_user_token(
settings.USERNAME, settings.scope, client_id=settings.SPOTIPY_CLIENT_ID, client_secret=settings.SPOTIPY_CLIENT_SECRET,
redirect_uri=settings.SPOTIPY_REDIRECT_URI)
settings.USERNAME,
settings.scope,
client_id=settings.SPOTIPY_CLIENT_ID,
client_secret=settings.SPOTIPY_CLIENT_SECRET,
redirect_uri=settings.SPOTIPY_REDIRECT_URI,
)
self.sp = spotipy.Spotify(auth=self.token)
self.skiped=pd.DataFrame()
self.played_emtirely=pd.DataFrame()

def _update_scope(self, scope: str):
self.token = spotipy.util.prompt_for_user_token(
settings.USERNAME,
settings.scope,
client_id=settings.SPOTIPY_CLIENT_ID,
client_secret=settings.SPOTIPY_CLIENT_SECRET,
redirect_uri=settings.SPOTIPY_REDIRECT_URI,
)
self.sp = spotipy.Spotify(auth=self.token)
return None

def skip_current_song(self) -> None:
self._update_scope(scope="user-modify-playback-state")
self.sp.next_track()
6 changes: 3 additions & 3 deletions notebooks/skiptify_calc_distance.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -2903,7 +2903,7 @@
],
"metadata": {
"kernelspec": {
"display_name": "Python 3.9.13 ('base')",
"display_name": "Python 3.10.6 (conda)",
"language": "python",
"name": "python3"
},
Expand All @@ -2917,12 +2917,12 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
"version": "3.10.6"
},
"orig_nbformat": 4,
"vscode": {
"interpreter": {
"hash": "c6e4e9f98eb68ad3b7c296f83d20e6de614cb42e90992a65aa266555a3137d0d"
"hash": "d2516f5993404e9e349ea047f12238c69ae1d787a6ad5240fc8c2c3492776c28"
}
}
},
Expand Down
6 changes: 3 additions & 3 deletions notebooks/skiptify_generate_data.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,7 @@
],
"metadata": {
"kernelspec": {
"display_name": "Python 3.9.13 ('base')",
"display_name": "Python 3.10.6 (conda)",
"language": "python",
"name": "python3"
},
Expand All @@ -353,12 +353,12 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
"version": "3.10.6"
},
"orig_nbformat": 4,
"vscode": {
"interpreter": {
"hash": "c6e4e9f98eb68ad3b7c296f83d20e6de614cb42e90992a65aa266555a3137d0d"
"hash": "d2516f5993404e9e349ea047f12238c69ae1d787a6ad5240fc8c2c3492776c28"
}
}
},
Expand Down
4 changes: 4 additions & 0 deletions pytest.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[tool.pytest.ini_options]
markers = [
"spotify_api_test: spotify api tests",
]
Empty file added test/__init__.py
Empty file.
6 changes: 5 additions & 1 deletion test/test_spotify_api.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import pytest
from backend.src.utils.api_interface import SPOTIFY_API_INTERFACE
from backend.src.spotify_api.api_interface import SPOTIFY_API_INTERFACE


@pytest.mark.spotify_api_test
def test_get_history():
interface = SPOTIFY_API_INTERFACE()
interface.get_song_history()


if __name__ == "__main__":
test_get_history()

0 comments on commit 1258f70

Please sign in to comment.