Skip to content

Commit

Permalink
Detect if song is instrumental (#20)
Browse files Browse the repository at this point in the history
* add starring discord

* correct colour

* file separation and improvements to the discord bot

* remove original elements form main file

* include username in discord message

* rename webhook handler fn

* remove mocking utils used for mock run

* reformat and rearrange code

* fix PEP8 errors

* fix PEP8 errors

* fix formatting for long lines

* perfect discord embed message

* add comments and improve formatting

* minor pep8 fix

* minor pep8 fix

* remove old code

* change server vanity presence

* remove discord_bot.py

* remove references to discord

* review branched and correct logic

* remove discord depenency

* 	moved helper to utils.py

* fix import error

* reformat SQLALCHEMY_DATABASE_URI

* add logic to determine instrumentalness

* update logic

* update grammar

* add first test

* fix object error

* update test

* fix typo in test

* rewrite test

* add helper function to test instrumental qualities

* fix broken test

* remove invalid test
  • Loading branch information
JamesVStone committed Feb 24, 2020
1 parent f8d9870 commit 3383cd6
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 7 deletions.
29 changes: 25 additions & 4 deletions swaglyrics_backend/issue_maker.py
Expand Up @@ -2,13 +2,16 @@
import os import os
import re import re
import time import time

import git import git
import requests import requests
from flask import Flask, request, abort, render_template from flask import Flask, request, abort, render_template
from flask_limiter import Limiter from flask_limiter import Limiter
from flask_limiter.util import get_ipaddr from flask_limiter.util import get_ipaddr
from flask_sqlalchemy import SQLAlchemy from flask_sqlalchemy import SQLAlchemy

from datetime import datetime as dt from datetime import datetime as dt

from requests.auth import HTTPBasicAuth from requests.auth import HTTPBasicAuth
from swaglyrics import __version__ from swaglyrics import __version__
from swaglyrics.cli import stripper, spc from swaglyrics.cli import stripper, spc
Expand All @@ -25,6 +28,7 @@
default_limits=["1000 per day"] default_limits=["1000 per day"]
) )



# database env variables # database env variables
username = os.environ['USERNAME'] username = os.environ['USERNAME']
passwd = os.environ['PASSWD'] passwd = os.environ['PASSWD']
Expand Down Expand Up @@ -221,7 +225,8 @@ def create_issue(song, artist, version, stripper='not supported yet'):


def check_song(song, artist): def check_song(song, artist):
""" """
Check if song, artist pair exist on Spotify or not using the Spotify API. Check if song, artist pair exist on Spotify or not using the Spotify API. Also checks if song is instrumental
in which case it would not have lyrics.
This is done to verify if the data received is legit or not. An exact comparison is done since the data is This is done to verify if the data received is legit or not. An exact comparison is done since the data is
supposed to be from Spotify in the first place. supposed to be from Spotify in the first place.
Expand All @@ -237,12 +242,28 @@ def check_song(song, artist):
except KeyError: except KeyError:
return False return False
if data: if data:
print(data[0]['artists'][0]['name'], data[0]['name']) track = data[0]
if data[0]['name'] == song and data[0]['artists'][0]['name'] == artist: print(track['artists'][0]['name'], track['name'])
if track['name'] == song and track['artists'][0]['name'] == artist:
print(f'{song} and {artist} legit on Spotify') print(f'{song} and {artist} legit on Spotify')
return True if not check_song_instrumental(track, headers):
return True
print(f'{song} by {artist} seems to be instrumental')
else: else:
print(f'{song} and {artist} don\'t seem legit.') print(f'{song} and {artist} don\'t seem legit.')

return False


def check_song_instrumental(track, headers):
"""
Helper function to determine if song is instrumental using spotify audio features API.
Returns true if it considers a song to be instrumental.
"""
metadata = requests.get(f'https://api.spotify.com/v1/audio-features/{track["id"]}', headers=headers).json()
if metadata["instrumentalness"] > 0.45 and metadata["speechiness"] < 0.04:
return True
return False return False




Expand Down
6 changes: 4 additions & 2 deletions tests/test_issue_maker.py
Expand Up @@ -71,12 +71,14 @@ def test_check_song_returns_false_on_bad_response(self, requests_mock, response_
self.assertFalse(check_song("Miracle", "Caravan Palace")) self.assertFalse(check_song("Miracle", "Caravan Palace"))


@patch('swaglyrics_backend.issue_maker.get_spotify_token', return_value={"access_token": ""}) @patch('swaglyrics_backend.issue_maker.get_spotify_token', return_value={"access_token": ""})
@patch('requests.Response.json') @patch('requests.Response.json', return_value={'error', 'yes'})
@patch('requests.get', return_value=Response()) @patch('requests.get', return_value=Response())
def test_that_check_song_returns_true(self, mock_get, mock_response, spotify_token): @patch('swaglyrics_backend.issue_maker.check_song_instrumental', return_value=False)
def test_that_check_song_returns_true(self, check_instrumental, mock_get, mock_response, spotify_token):
from swaglyrics_backend.issue_maker import check_song from swaglyrics_backend.issue_maker import check_song
mock_response.return_value = get_correct_spotify_search_json( mock_response.return_value = get_correct_spotify_search_json(
'correct_spotify_data.json') 'correct_spotify_data.json')

self.assertTrue(check_song("Miracle", "Caravan Palace")) self.assertTrue(check_song("Miracle", "Caravan Palace"))


@patch('swaglyrics_backend.issue_maker.get_spotify_token', return_value={"access_token": ""}) @patch('swaglyrics_backend.issue_maker.get_spotify_token', return_value={"access_token": ""})
Expand Down
2 changes: 1 addition & 1 deletion tests/test_utils.py
@@ -1,4 +1,4 @@
from unittest.mock import patch from unittest.mock import patch, Mock


from werkzeug.exceptions import ImATeapot from werkzeug.exceptions import ImATeapot


Expand Down

0 comments on commit 3383cd6

Please sign in to comment.