Example #1
0
import urllib2
import json
import spotipy
import spotipy.util as util
import requests
import base64

from spotipy.oauth2 import SpotifyClientCredentials

ci='clientid'
cs='clientsecret'

#replace with actual stuff
ccm=SpotifyClientCredentials(client_id='ba8d2826c2824677b73ebff71ca27785', client_secret='f4e3f64683e84da8a616c6da083fa287')

token=ccm.get_access_token()
sp=spotipy.Spotify(auth=token)


def get_new_albums():
    '''
    Fetches new album data from Spotify.
    
    Returns list of albums. Each album is a dictionary containing values for the name, artist, album art, and a list of tracks. Each track in the list is a dictionary containing values for the name, artist, and Spotify URI (to be implemented with playing tracks). 

    '''
    print 'INSIIIDE'
    data=sp.new_releases(country=None, limit=20, offset=0)
    albums_data=data['albums']['items']
    #print albums_data[0].keys()
    albums_uris=[]
!pip install spotipy

import argparse
import pprint
import sys
import os
import subprocess
import json
import spotipy
import spotipy.util as util
import pandas as pd
import time
from spotipy.oauth2 import SpotifyClientCredentials


client_credentials_manager = SpotifyClientCredentials(client_id= '77fbff4d863a482d82ce8fa6dbbc9f1b', client_secret='55c4c40ecaf445c0b9d742b5099d6888')
username = "******"




def show_tracks(tracks):
    for i, item in enumerate(tracks['items']):
        track = item['track']
        print (" %d %s %s" % (i, track['artists'][0]['name'],track['name']))

def get_track_features(track_id,sp):
    if track_id is None:
        return None
    else:
        features = sp.audio_features([track_id])
Example #3
0
# -*- coding: utf-8 -*-

import random
import spotipy
import spotipy.util as util
from spotipy.oauth2 import SpotifyClientCredentials

keys = dict([line.split() for line in open('keys')])
SPOTIPY_CLIENT_ID = keys['SpotifyID']
SPOTIPY_CLIENT_SECRET = keys['SpotifySecret']

client_credentials_manager = SpotifyClientCredentials(SPOTIPY_CLIENT_ID,
                                                      SPOTIPY_CLIENT_SECRET)
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

emotions = {
    'neutral': ['neutral', 'popular', 'hits', 'dance', 'hot'],
    'happiness': ['happiness', 'happy', 'cheerful', 'summer', 'upbeat'],
    'anger': ['angry', 'anger', 'rage', 'upset'],
    'sadness': ['sad', 'sadness', 'emo', 'winter'],
    'fear': ['calm', 'calming', 'relax']
}


def get_playlist(emotion):
    keyword = random.choice(emotions[emotion])
    random_int = random.randint(0, 75)
    playlist_list = sp.search(keyword,
                              limit=10,
                              offset=random_int,
                              type='playlist',
from pandas.io import sql
import pandas as pd
from sqlalchemy import create_engine
import spotipy as s
from spotipy.oauth2 import SpotifyClientCredentials

from keys import client_ID, client_secret, oauth_token

client_credentials_manager = SpotifyClientCredentials(
    client_id=client_ID, client_secret=client_secret)
spotify = s.Spotify(client_credentials_manager=client_credentials_manager)

# Establish link to the database
engine = create_engine('postgresql://jamesrogol@localhost:5432/bond')

tracks = sql.read_sql("SELECT track_id FROM songs;", engine)
tid = tracks['track_id'][0]

analysis = spotify.audio_analysis(tid)
def spotipy_api():
    sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials(
        client_id=client_id, client_secret=client_secret))

    return sp
Example #6
0
def spotify_dl():
    """Main entry point of the script."""
    parser = argparse.ArgumentParser(prog='spotify_dl')
    parser.add_argument('-l', '--url', action="store",
                        help="Spotify Playlist link URL", type=str, required=True)
    parser.add_argument('-o', '--output', type=str, action='store',
                        help='Specify download directory.', required=True)
    parser.add_argument('-d', '--download', action='store_true',
                        help='Download using youtube-dl', default=True)
    parser.add_argument('-f', '--format_str', type=str, action='store',
                        help='Specify youtube-dl format string.',
                        default='bestaudio/best')
    parser.add_argument('-m', '--skip_mp3', action='store_true',
                        help='Don\'t convert downloaded songs to mp3')
    parser.add_argument('-s', '--scrape', action="store",
                        help="Use HTML Scraper for YouTube Search", default=True)
    parser.add_argument('-V', '--verbose', action='store_true',
                        help='Show more information on what''s happening.')
    parser.add_argument('-v', '--version', action='store_true',
                        help='Shows current version of the program')
    args = parser.parse_args()

    if args.version:
        print("spotify_dl v{}".format(VERSION))
        exit(0)

    db.connect()
    db.create_tables([Song])
    if os.path.isfile(os.path.expanduser('~/.spotify_dl_settings')):
        with open(os.path.expanduser('~/.spotify_dl_settings')) as file:
            config = json.loads(file.read())

        for key, value in config.items():
            if value and (value.lower() == 'true' or value.lower() == 't'):
                setattr(args, key, True)
            else:
                setattr(args, key, value)

    if args.verbose:
        log.setLevel(DEBUG)

    log.info('Starting spotify_dl')
    log.debug('Setting debug mode on spotify_dl')

    if not check_for_tokens():
        exit(1)

    sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials())
    log.debug('Arguments: {}'.format(args))

    if args.url:
        valid_item = validate_spotify_url(args.url)

    if not valid_item:
        sys.exit(1)

    if args.output:
        item_type, item_id = parse_spotify_url(args.url)
        directory_name = get_item_name(sp, item_type, item_id)
        save_path = Path(PurePath.joinpath(Path(args.output), Path(directory_name)))
        save_path.mkdir(parents=True, exist_ok=True)
        log.info("Saving songs to: {}".format(directory_name))

    songs = fetch_tracks(sp, item_type, args.url)
    if args.download is True:
        download_songs(songs, save_path, args.format_str, args.skip_mp3)
Example #7
0
import logging
import random
import sys
import spotipy
import os
import time
import numpy as np
import pandas as pd
from spotipy.oauth2 import SpotifyClientCredentials
import os.path
import multiprocessing

# spotify credentials
client_credentials_manager = SpotifyClientCredentials()
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

# open the file and read the contents-List of artists to find discography
f = open("ticket_concert_artists.csv")
lines = f.readlines()  # don't read in header
results = []

for x in lines:
    results.append(x.split(',')[0])

f.close()

random.shuffle(results)
# results.sort()
# print(results)

# failed_searches = []
Example #8
0
def autentica(client_id, client_secret):
    client_credentials_manager = SpotifyClientCredentials(
        client_id, client_secret)
    return spotipy.Spotify(
        client_credentials_manager=client_credentials_manager)
Example #9
0
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import json
import requests

dates = [year for year in range(2008, 2017)]
danceability = []
energy = []
speechiness = []
successes = []
for year in dates:
    _id_ = []
    chart = billboard.ChartData('hot-100', date=str(year) + '-12-31')
    for song in chart:
        _id_.append(str(song.spotifyID))
    client_credentials_manager = SpotifyClientCredentials(
        'Client ID', 'Client Secret')
    sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
    for i in _id_:
        try:
            tid = 'spotify:track:' + i
            analysis = sp.audio_features(tid)
            results = json.dumps(analysis, indent=4)
            results = json.loads(results)
            danceability.append(results[0]['danceability'])
            energy.append(results[0]['energy'])
            speechiness.append(results[0]['speechiness'])
        except requests.exceptions.HTTPError:
            pass
        except TypeError:
            pass
    for song in chart:
Example #10
0
market = ["US"]

# spotipy keys, put in env file
SP_CLIENT_ID = "--keys--"
SP_CLIENT_SECRET = "--keys--"

# genius keys
GENIUS_ACCESS_TOKEN = "--keys--"
genius_api = genius.Genius(GENIUS_ACCESS_TOKEN)
genius.verbose = True  # Keep status messages on
genius.remove_section_headers = False  # Remove section headers (e.g. [Chorus]) from lyrics when searching
genius.excluded_terms = ["(Remix)", "(Live)"
                         ]  # Exclude songs with these words in their title

# creds
credentials = SpotifyClientCredentials(client_id=SP_CLIENT_ID,
                                       client_secret=SP_CLIENT_SECRET)

# token access
token = credentials.get_access_token()
spotify = spotipy.Spotify(auth=token)


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/output', methods=['POST'])
def output():
    # connecting html to request
    # user inputs song name here
def getSpotifyClient(clientID, clientSecret):
    client_credentials_manager = SpotifyClientCredentials(
        clientID, clientSecret)
    return spotipy.Spotify(
        client_credentials_manager=client_credentials_manager)
Example #12
0
    for task in queue_iter(q, block=False):
        try:
            search_artist(conn, spotify, task)
            conn.commit()
            # print(task)
        except Exception as e:
            print("Error %s : %s" % (e, traceback.format_exc()))
    conn.close()


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument("--count", type=int, default=1)
    parser.add_argument("--threads", type=int, default=10)
    args = parser.parse_args()

    client_credentials_manager = SpotifyClientCredentials(
        client_id=config.config["SPOTIFY_CLIENTID"],
        client_secret=config.config["SPOTIFY_SECRET"]
    )
    queue = Queue()

    conn = psycopg2.connect(config.connstr())
    for task in get_tasks(conn, args.count):
        queue.put(task)
    conn.close()

    queue_thread_exec(queue, func=worker, thread_count=args.threads)
try:
    from bs4 import BeautifulSoup
except ImportError:
    print('beautifulsoup4 is not installed. You can install this by executing the following in a terminal:')
    print('\t"{0}" -m pip install beautifulsoup4'.format(PYTHON_EXECUTABLE))
    input()
    sys.exit(1)


# Get Keys
with open('settings.json') as data_file:
    settings = json.load(data_file)

# Create Spotify object
print('[Top Level] Setting up Spotify object...')
client_credentials_manager = SpotifyClientCredentials(client_id=settings['spotify']['client_id'], client_secret=settings['spotify']['client_secret'])
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
sp.trace=False


def chunks(l, n):
    # Thanks to http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]

def stripString(text):
    return "".join([i for i in text if i not in [i for i in '/\\:*?"><|']])

def my_hook(d):
    if '_percent_str' in d:
 def spotify_connection(self):
     client_credentials_manager = SpotifyClientCredentials(
         self.CLIENT_ID, self.CLIENT_SECRET)
     sp = spotipy.Spotify(
         client_credentials_manager=client_credentials_manager)
     return sp
Example #15
0
from flask import Flask, render_template, request, Response
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import json

sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(
    client_id="your api id", client_secret="your client secret"))

app = Flask(__name__)


@app.route('/', methods=['GET', 'POST'])
def main():
    songs = []
    error = False
    if request.method == "GET":
        return render_template("index.html")
    elif request.method == "POST":
        song_name = request.form["music"].lower()
        results = sp.search(q=song_name, type="track", limit=1)
        if len(results["tracks"]["items"]) == 0:
            error = True
        else:
            id_song = results['tracks']['items'][0]['id']
            name_song = results["tracks"]["items"][0]["external_urls"][
                "spotify"]
            print("id song ", name_song)
            songs = sp.recommendations(seed_tracks=[id_song],
                                       limit=20)["tracks"]
            if (len(songs) == 0):
                error = True
Example #16
0
def get_sp_token(client_id, client_secret):
    s = SpotifyClientCredentials(client_id, client_secret)
    token = s.get_access_token()
    return token
#----------------------------------------------------------------------------
if __name__ == '__main__':

    #Username
    username = '******'

    #Settings
    cmd1 = "export SPOTIPY_CLIENT_ID='5c7e874f0455484fa7f083ddfb00d6d3'"
    cmd2 = "export SPOTIPY_CLIENT_SECRET='aa12f51eb9be4159b7419d628f99a9ee'"
    cmd3 = "export SPOTIPY_REDIRECT_URI='http://www.gijsjoostbrouwer.com'"
    cmd4 = "export YOUTUBE_DEV_KEY='AIzaSyDygNhHkHUQLWSNz-AFDFe33eU4n2FdFyU'"

    #Init
    my_client_id, my_client_secret = clientIds()
    client_credentials_manager = SpotifyClientCredentials(
        client_id=my_client_id, client_secret=my_client_secret)
    sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

    # #Get Playlists
    # idlist = []
    # playlists = sp.user_playlists(username)
    # for playlist in playlists['items']:
    #     if playlist['owner']['id'] == username:
    #         idlist.append(playlist['id'])
    #         print(playlist['id'],playlist['name'])

    # #Download Command
    # # playlist_id = '3OcLmMGOaKBhDAPji7mTf3'
    # playlist_id = '624HWemwkr07H8B6GyLC9y'
    playlist_id = '0NLAC7syToc2g6ImWybVB4'
    cmd5 = 'spotify_dl -d -u ' + username + ' -p ' + playlist_id + ' -o . '
print("Question 1")
# 1 Import the spotipy API to be able to use it in this challenge
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
# We'll need this to print the resulting data nicely
import json

# To access authorized Spotify data, do not edit these next few lines, they are just needed to make our function calls actually work
from spotipy.oauth2 import SpotifyClientCredentials

# Do not edit these unless you have your own Spotify Developer account
CLIENT_ID = '99b361927f674edfb28a342956235d47'
CLIENT_SECRET = '3657ba71ed0d480fb415e96b4cbef89c'

client_credentials_manager = SpotifyClientCredentials(
    client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
# spotify object to access API
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)


# The results for the function calls we will be making are a little bit hard to parse, so formatting a string from the Python JSON object might help here. Here, we've provided a function called `jprint()` that you can call on the output of your search to try to look at the search result as a formatted string
# you do not have to edit this function at all!!!
def jprint(obj):
    # create a formatted string of the Python JSON object
    text = json.dumps(obj, sort_keys=True, indent=4)
    print(text)


# IMPORTANT NOTE: FOR THIS CHALLENGE, EVERY FUNCTION YOU CALL WILL HAVE TO START WITH sp (i.e. sp.search() and whatever else), BECAUSE THAT IS THE NAME OF THE SPOTIPY OBJECT WE CREATED! WITHOUT THE sp, YOUR FUNCTION CALLS WILL NOT WORK!!!

print("Question 2")
Example #19
0
import pandas as pd
import numpy as np
import sqlite3
import re

import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

#importing local class
from spotipy_query import spotipy_query, search_loop

sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())

all_songs = pd.read_csv('Music.txt', sep='\t', header=0, engine='python')

with open('missing_track_insert.sql') as f:
    failed_to_find = f.read()

missing_db = sqlite3.connect('spotipy.db')

#triming and renaming columns

first_range = list(range(0, 5))

second_range = [7, 12]
total_range = first_range + second_range

all_songs = all_songs.iloc[:, total_range]

#converting dtypes
str_list = ['Name', 'Artist', 'Album', 'Year']
Example #20
0
def isPlaying():
    try:
        if spoyifyObj.currently_playing()["is_playing"]:
            return True
        return False
    except:
        return False


trackLists = []
address = '127.0.0.1'
port = 8000
bsize = 1024
scope = 'playlist-modify-public streaming user-modify-playback-state user-read-playback-state user-read-currently-playing'
client_credentials_manager = SpotifyClientCredentials(
    '221e9a5fac5c4f40bb2de9c33ce7a863', '8c5e85b7165840bbb605b43924952889')
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
name = input("enter username ")


def addToQueue():
    artistName = input("enter an artist name ")
    results = spoyifyObj.search(artistName, 1, 0, "artist")
    artist = results['artists']['items'][0]
    print(artist['name'] + " has " + str(artist['followers']['total']) +
          " followers , and his genre is " + artist['genres'][0])
    webbrowser.open(artist['images'][0]['url'])
    artistId = artist["id"]
    trackUri = []
    trackArt = []
    z = 1
'''This class parses retrieved Spotify API data for both playlists and albums'''
import os
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import qrcode
import PIL as pillow
import re

os.environ["SPOTIPY_CLIENT_ID"] = '19d46d1de89a44c9813248a047e1788f'
os.environ["SPOTIPY_CLIENT_SECRET"] = 'bdffc7ce17c34d2fb13883afb54d7cf2'

auth_manager = SpotifyClientCredentials()
sp = spotipy.Spotify(auth_manager=auth_manager)


def get_playlist_id(playlist_url):
    result = re.search('playlist/(.*)', playlist_url)
    get_id = result.group(1).split('?')[0]
    playlist_id = 'spotify:playlist:' + get_id
    return playlist_id


def get_album_id(album_url):
    result = re.search('album/(.*)', album_url)
    get_id = result.group(1).split('?')[0]
    album_id = 'spotify:album:' + get_id
    return album_id


def get_playlist_title(playlist_id):
    results = sp.playlist(playlist_id)
Example #22
0
import datetime
import spotipy
import spotipy.util
from spotipy import oauth2
from spotipy.oauth2 import SpotifyClientCredentials

app = Bottle()

# globals
logging.basicConfig(level=logging.DEBUG,
                    format="%(asctime)s - %(levelname)s - %(message)s")
CLIENT_ID = "e29426dfb22c41cdbc92122fbb9c398c"
CLIENT_SECRET = "837fd2824bec47e5a003419165674bdd"
SCOPE = "user-top-read user-read-recently-played playlist-modify-public playlist-modify-private"
CACHE = ".spotifyoauthcache"
CLIENT_CREDENTIALS = SpotifyClientCredentials(client_id=CLIENT_ID,
                                              client_secret=CLIENT_SECRET)
SP_OAUTH2 = oauth2.SpotifyOAuth(client_id=CLIENT_ID,
                                client_secret=CLIENT_SECRET,
                                redirect_uri="http://localhost:8000/verified",
                                scope=SCOPE,
                                cache_path=CACHE)
LIMIT = 50
OFFSET = 0

TEMPLATE_PATH.insert(0, "")

# global functions


def get_token():
    access_token = ""
Example #23
0
import os
import re
import pandas as pd
from tqdm.notebook import tqdm
from bs4 import BeautifulSoup
from urllib.parse import urljoin

import spotipy
import requests
from spotipy.oauth2 import SpotifyClientCredentials
from dotenv import load_dotenv

load_dotenv()

client_credentials_manager = SpotifyClientCredentials(
    client_id=os.environ['SPOTIPY_CLIENT_ID'],
    client_secret=os.environ['SPOTIPY_CLIENT_SECRET']
)

sp = spotipy.Spotify(
    client_credentials_manager=client_credentials_manager
)

def find_band_spotify(band_name):
    """
    For a given band name, find Spotify profile
    """
    results = sp.search(q='artist:' + band_name, type='artist')
    items = results['artists']['items']
    return items

Example #24
0
import spotipy
import sys
from spotipy.oauth2 import SpotifyClientCredentials

spotify = spotipy.Spotify(auth_manager=SpotifyClientCredentials())

if len(sys.argv) > 1:
    name = ' '.join(sys.argv[1:])
else:
    name = 'Radiohead'

results = spotify.search(q='artist:' + name, type='artist')
items = results['artists']['items']
if len(items) > 0:
    artist = items[0]
    print(artist['name'], artist['images'][0]['url'])
Example #25
0
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import os

SPOTIPY_CLIENT_ID = os.getenv("SPOTIPY_CLIENT_ID")
SPOTIPY_CLIENT_SECRET = os.getenv("SPOTIPY_CLIENT_SECRET")

sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials(
    client_id=SPOTIPY_CLIENT_ID, client_secret=SPOTIPY_CLIENT_SECRET))


def spotify_first_search(keyword):
    results = sp.search(q=keyword, limit=1)
    result_dict = {}
    result_dict["name"] = results['tracks']['items'][0]['name']
    result_dict["artist_name"] = results['tracks']['items'][0]['album'][
        'artists'][0]['name']
    result_dict["artist_url"] = results['tracks']['items'][0]['album'][
        'artists'][0]['external_urls']['spotify']
    result_dict["album_name"] = results['tracks']['items'][0]['album']['name']
    result_dict["album_url"] = results['tracks']['items'][0]['album'][
        'external_urls']['spotify']
    result_dict["image_url"] = results['tracks']['items'][0]['album'][
        'images'][0]['url']
    result_dict["release_date"] = results['tracks']['items'][0]['album'][
        'release_date']
    result_dict["popularity"] = results['tracks']['items'][0]['popularity']
    result_dict["available_country"] = str(
        results['tracks']['items'][0]['available_markets'])[1:-1]
    result_dict["preview_url"] = results['tracks']['items'][0]['preview_url']
    result_dict["total_result"] = results['tracks']['total']
def getsphandle():
    client_credentials_manager = SpotifyClientCredentials(client_secret='0d2e381e77fa48c9b0504b4559eb1613',
                                                      client_id='60512ae1d0614bea93fab9ba5f58e73a')

    sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
    return sp
Example #27
0
def recommendations(artist, title):
    #TODO: store songdata in a json file so we don't have to do this over and over
    #TODO: add album art to each track in this csv
    docLabels = []
    with open('data/songdata.csv') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        line_count = 0
        for row in csv_reader:
            if line_count != 0:
                docLabels.append(row[1] + " ~ " + row[0])
                if len(docLabels) % 100 == 0:
                    print("\rReading documents: %d" % len(docLabels),
                          end='',
                          flush=True)
            line_count += 1

    url = 'matcher.track.get?q_track={}&q_artist={}&format={}'.format(
        title, artist, 'json')
    req_url = 'http://api.musixmatch.com/ws/1.1/{}&apikey={}'.format(
        url, os.environ.get("MUSIX_API_KEY"))
    data = requests.get(req_url)
    data = json.loads(data.text)
    if data["message"]["header"]["status_code"] == 200:

        matched_artist = data["message"]["body"]["track"]["artist_name"]
        matched_title = data["message"]["body"]["track"]["track_name"]

        flash('requested song: {} ~ {}'.format(matched_artist, matched_title))

        client_credentials_manager = SpotifyClientCredentials(
            client_id=os.environ.get("SPOTIFY_CLIENT_ID"),
            client_secret=os.environ.get("SPOTIFY_CLIENT_SECRET"))
        spotify = spotipy.Spotify(
            client_credentials_manager=client_credentials_manager)

        results = spotify.search(q='track:' + matched_title + ' artist:' +
                                 matched_artist,
                                 type='track')
        track = results['tracks']['items'][0]

        message = Markup("<img src='{url}' />".format(
            url=track["album"]["images"][1]["url"]))
        flash(message, category='success')

        message = Markup(
            "<audio controls src='{url}' />".format(url=track["preview_url"]))
        flash(message, category='success')

        matched_artist = matched_artist.lower()
        matched_title = matched_title.lower()

        # remove all except alphanumeric characters from matched_artist and matched_title
        matched_artist = re.sub('[^A-Za-z0-9]+', "", matched_artist)
        matched_title = re.sub('[^A-Za-z0-9]+', "", matched_title)

        if matched_artist.startswith(
                "the"
        ):  # remove starting 'the' from matched_artist e.g. the who -> who
            matched_artist = matched_artist[3:]

        matched_id = data["message"]["body"]["track"]["track_id"]
        url = 'track.lyrics.get?track_id={}&format={}'.format(
            matched_id, 'json')
        req_url = 'http://api.musixmatch.com/ws/1.1/{}&apikey={}'.format(
            url, os.environ.get("MUSIX_API_KEY"))
        data = requests.get(req_url)
        data = json.loads(data.text)
        lyrics = data["message"]["body"]["lyrics"]["lyrics_body"].split(
            "...")[0]

        lyrics = lyrics.strip()
        lyrics = lyrics.replace('\n', ' ')
        lyrics = re.sub("[\(\[].*?[\)\]]", "", lyrics)

        model = Doc2Vec.load("d2v.model")
        #to find the vector of a document which is not in training data
        test_data = word_tokenize(lyrics.lower())
        v1 = model.infer_vector(doc_words=test_data,
                                alpha=0.025,
                                min_alpha=0.001,
                                steps=55)
        similar_v1 = model.docvecs.most_similar(positive=[v1])

        for song in similar_v1:
            flash('recommended song: {}'.format(docLabels[int(song[0])]))
    else:
        flash('Sorry, we did not find the track "{}" by {}. Try again?'.format(
            title, artist))

    return render_template('recommendations.html',
                           title='Your recommendations')
Example #28
0
 def __init__(self):
     # the_secret_function() # credenciales
     # podriamos usar herencia, de momento asi vale:
     self.sp = spotipy.Spotify(
         client_credentials_manager=SpotifyClientCredentials())
from spotipy.oauth2 import SpotifyClientCredentials
import spotipy
from youtube_search import YoutubeSearch

PLAYLISTS = [['Accidental','https://open.spotify.com/playlist/0zJ8hC8YJOcHYuk5nMPFm8?si=U6Kyom3XQ32reSuVgl2uhA', "PL59eqqQABruMQOPlUVcVsIid685ZdwDjf"],
['TimePass','https://open.spotify.com/playlist/6gADLrLFK1kXgEEOsENi1c', "PL59eqqQABruMSx6VSy1hbkBhG4XwtgSuy"],
['CHILLS','https://open.spotify.com/playlist/3zs3QOLX8bASY5oV2dmEQw', 'PL59eqqQABruN3GyAPiPnQ6Jq-TngWjT-Y'],
['Programming & Coding Music','https://open.spotify.com/playlist/6vWEpKDjVitlEDrOmLjIAj', 'PL59eqqQABruNew5O0cRvomfbU6FI0RGyl'],
['Spanish','https://open.spotify.com/playlist/75QJ1JeFaeSm0uH1znWxb0?si=Lt4kd-RARBu2TQz35RAQiQ', 'PL59eqqQABruM3TLAGthvgW10c1R6omGwq']
]
client_credentials_manager = SpotifyClientCredentials(client_id='{client_id}',
                client_secret='{client_secret}')
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)



CONTAINER = []
for playlist in PLAYLISTS:
    Name,Link,playlistid = playlist
    playlistcard = []
    count = 0
    PlaylistLink = "http://www.youtube.com/watch_videos?video_ids="
    for i in (sp.playlist_tracks(Link)['items']):
        if count == 50:
            break
        try:
            song = i['track']['name'] + i['track']['artists'][0]['name']
            songdic = (YoutubeSearch(song, max_results=1).to_dict())[0]
            playlistcard.append([songdic['thumbnails'][0],songdic['title'],songdic['channel'],songdic['id']])
            PlaylistLink += songdic['id'] + ','
        except:
Example #30
0
import sys
from spotipy.oauth2 import SpotifyClientCredentials
import spotipy
import pprint
import pandas as pd
import pdb
import re

# client_id = "fac9c94efcc04895b83bd73aa53bbbf8"
# client_secret = "15a3224aa35242cba201e933284aedc5"

client_credentials_manager = SpotifyClientCredentials(
    client_id="CLIENT_ID_HERE", client_secret="CLIENT_SECRET_HERE")
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)


def getRelated(id):
    label = []
    popularity = []
    followers = []
    ids = []

    for i in sp.artist_related_artists(id)['artists']:
        # print(i['id'],i['name'],i['followers'],i['href'],sep=' === ')
        label.append(i['name'])
        followers.append(i['followers']["total"])
        ids.append(i['id'])
        popularity.append(i["popularity"])

        dataf = pd.DataFrame({
            'Id': ids,
Example #31
0
	def __init__(self):
		oauth = SpotifyClientCredentials(self.client_id, self.client_secret)
		token = oauth.get_access_token()
		self.sp = spotipy.Spotify(auth=token)
Example #32
0
#%%
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import pandas as pd
import numpy as np
import secret

client_id = secret.client_id
client_secret = secret.client_secret
username = secret.username
p_id = secret.playlist_id
credentials = SpotifyClientCredentials(client_id, client_secret)
sp = spotipy.Spotify(client_credentials_manager = credentials)
NaN = np.nan

#%%
def show_tracks(results, array):
    for i, item in enumerate(results['items']):
        track = item['track']
        array.append(track['id'])

def get_track_ids(username, playlist_id):
    ids = []
    playlist = sp.user_playlist(username, playlist_id)
    tracks = playlist['tracks']
    show_tracks(tracks, ids)
    while tracks['next']:
            tracks = sp.next(tracks)
            show_tracks(tracks, ids)
    return ids