Exemple #1
0
def search_song(spotipy, arq):
    not_found = []
    track_ids = []

    for line in arq:
        if not line[0].isdigit():
            continue
        song = line.split('. ', 1)[1]
        song = song.replace(" – ", " - ")
        if '-' not in song:
            continue
        (a, t) = split_artist_track(song)
        result = spotipy.search(q='artist: ' + a + ' track: ' + t,
                                limit=1,
                                type='track')
        if len(result['tracks']['items']) == 0:
            result = spotipy.search(q=song, limit=1, type='track')
            if len(result['tracks']['items']) == 0:
                result = spotipy.search(q='track: ' + t,
                                        limit=20,
                                        type='track')
                if len(result['tracks']['items']) == 0:
                    not_found.append(line)
                    print(a, ' - ', t, ': not found.')
                else:
                    msg_t3 = a + ' - ' + t + ': not found.'
                    for i in result['tracks']['items']:
                        for nome in i['artists']:
                            if nome['name'] in a:
                                track_ids.append(i['id'])
                                msg_t3 = a + ' - ' + t + ': found.'
                                break
                    if 'not found' in msg_t3:
                        not_found.append(line)
                    print(msg_t3)
            else:
                track_ids.append(result['tracks']['items'][0]['id'])
                print(a, ' - ', t, ': found.')
        else:
            track_ids.append(result['tracks']['items'][0]['id'])
            print(a, ' - ', t, ': found.')
    return track_ids, not_found
def search_album(Entrada,session):
    connect_spotify(session,cox)
    results = spotipy.search(Entrada)
    songs = {}
    for a in results['tracks']["items"]:
        image = a["album"]["images"][1]["url"]
        
        name = unicodedata.normalize("NFKD",a["name"]).encode("ascii","ignore")
        uri = unicodedata.normalize("NFKD",a["uri"]).encode("ascii","ignore")
        songs[name] = {"artista":a["artists"][0]["name"],"uri":uri,"cover":image,'preview_url':a["preview_url"]}
    return songs 
def search_music(Entrada,session):
    
    connect_spotify(session,cox)
    results = spotipy.search(Entrada, limit=20)
    songs = {}
    for i in results['tracks']['items']:
        albumname=i['album']['name']
        name = unicodedata.normalize("NFKD",i['name']).encode("ascii","ignore")
        artist = unicodedata.normalize("NFKD",i["artists"][0]["name"]).encode("ascii","ignore")
        songs[name] = {"play":str(i["uri"]),"artista":artist,"imagen":i['album']['images'][1]['url'],'preview_url':i["preview_url"]}
    return songs
Exemple #4
0
def get_songs_id(spotipy, playlist, offset):
    '''
    Returns list of song IDs for each song in echonest playlist object.
    '''
    songs_id = []
    # full playlist
    if offset is None:
        playlist = playlist
    # playlist chunk
    elif isinstance(offset, int):
        playlist = playlist[offset:offset + 10]
    for item in playlist:
        q = "track:{} artist:{}".format(item.title.encode('utf-8'),
                                        item.artist_name.encode('utf-8'))

        result = spotipy.search(q, type='track', limit=1)
        if not result['tracks'].get('items'):
            continue
        spotify_id = spotipy.search(q, type='track', limit=1)['tracks']['items'][0]['id']
        songs_id.append(spotify_id)
    return songs_id
def search_artist(Entrada,session):
    connect_spotify(session,cox)
    artist = {}
    results = spotipy.search(q='artist:' + Entrada, type='artist')
    imagen_artist = results["artists"]["items"][0]["images"][0]["url"]
    names = str(results["artists"]["items"][0]["name"])
    generos = " "
    for a in (results["artists"]["items"][0]["genres"]):
        generos += a + " "
    results = spotipy.search(q=str(Entrada), limit=20)
    songs = {}
    for t in results['tracks']['items']:
        name = unicodedata.normalize("NFKD",t["name"]).encode("ascii","ignore")
        uri = unicodedata.normalize("NFKD",t["uri"]).encode("ascii","ignore")
        image = t["album"]["images"][1]["url"]
        songs[name] = {"artista":names,"play":uri,"imagen":image,'preview_url':t["preview_url"]}
    dic={}
    dic["imagen"]=imagen_artist
    dic["generos"]=generos
    dic["top"]=songs
    artist[names] = dic
    return tuple((artist,names))
Exemple #6
0
def get_songs_id(spotipy, playlist, offset):
    '''
    Returns list of song IDs for each song in echonest playlist object.
    '''
    songs_id = []
    # full playlist
    if offset is None:
        playlist = playlist
    # playlist chunk
    elif isinstance(offset, int):
        playlist = playlist[offset:offset + 10]
    for item in playlist:
        q = "track:{} artist:{}".format(item.title.encode('utf-8'),
                                        item.artist_name.encode('utf-8'))

        result = spotipy.search(q, type='track', limit=1)
        if not result['tracks'].get('items'):
            continue
        spotify_id = spotipy.search(q, type='track',
                                    limit=1)['tracks']['items'][0]['id']
        songs_id.append(spotify_id)
    return songs_id
Exemple #7
0
def spotify_genre_dict(genres):
    dictionary = {}
    for genre in tqdm(genres):
        artist_results = sp.search(q=f'genre:{genre}',
                                   type='artist')['artists']['items']
        artists = [(x['name'], x['id']) for x in artist_results]
        related_genres = [x['genres'] for x in artist_results]
        top_trax = [get_top_tracks(id) for artist, id in artists]
        top_trax = [item for sublist in top_trax for item in sublist]
        dictionary[genre] = {
            'related_genres': related_genres,
            'artists': [item for sublist in top_trax for item in sublist],
            'top_trax_feats': f.sp.audio_features(top_trax)
        }
        f.refresh_token()
    json.dump(dictionary, open('genre_definitions.json', 'w'))
    return dictionary
__author__ = 'Christina'


import spotipy
import string


## Input text from command line and remove punctuation marks.
poem = raw_input("Please enter poem: ")
cleanpoem = poem.translate(string.maketrans("",""), string.punctuation)


## Split poem into sepearte words to for a list (wordlist).
wordlist = cleanpoem.split()


### Search Spotify Metadata API for track matches to each item in cleanpoem array/list.
 """Needs work."""

spotify = spotipy.Spotify()

for word in wordlist:
    results = spotipy.search(q='track: ' + track, type='track')
    items = results['track']['spotify']
    if len(items) > 0:
        track = items[0]
        pprint.pprint(track['external_urls']['spotify'])
    else:
        print("Sorry, no matches found.")
import praw
import spotipy
from keys import spotify_keys, reddit_keys
from scopes import reddit_scopes, spotify_scopes
from spotipy.oauth2 import SpotifyClientCredentials
from spotipy.util import prompt_for_user_token

#sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials(
#    client_id=keys['client_id'], client_secret=keys['client_secret']
#))

sp = prompt_for_user_token(username="******",
                           scope=spotify_scopes.playlist_modify_public,
                           client_id=spotify_scopes.client_id,
                           client_secret=spotify_scopes.client_secret,
                           redirect_uri='http://127.0.0.1:8080')

results = sp.user_playlist_create(spotipy.search(q='weezer', limit=20))

for i, t in enumerate(results['tracks']['items']):
    print(" ", i, t['name'])
Exemple #10
0
def search(query, mode):
    return spotipy.search(query, type=mode)
Exemple #11
0
                                                      limit=int(qtdBusca))

            #lista as musicas mais tocadas no período
            for i, track in enumerate(chart_tracks):
                t = len(track)
                print(str(i + 1) + ")\t" + str(track[0]))
                tracks.append(str(track[0]))

            if input('Adicionar esta lista? (s/n)') == 's':
                for i, line in enumerate(tracks):
                    try:
                        txt = str(line)
                        print(str(i + 1) + ")\t" + str(txt)) + ' adicionada.'
                        (a, t) = functions.split_artist_track(txt)
                        res = spotipy.search(q='artist: ' + a + ' track: ' + t,
                                             limit=1,
                                             type='track',
                                             market='BR')
                        result = res['tracks']['items'][0]
                        track_ids.append(result['id'])
                    except Exception as e:
                        print('\nException:\n')
                        print(e)
                        print('\ntracks:\n')
                        print(tracks)
        elif aName == 'file':
            filepath = input('Caminho do arquivo: ')
            arquivo = open(filepath, 'r', encoding='utf-8')
            track_ids, not_found = functions.search_song(spotipy, arquivo)

        elif aName == 'feed':
            if not feed:
import spotify               # Se importa spotify, esta libreria nos permite construir nuestro cliente ya que nos facilita la reproducion de musica.
import unicodedata           # Esta libreria tiene como funcion la limpieza de strings de cualquier caracter no permitido en algun titulo 

session = spotify.Session()        #siempre en este programa se debe crear una session, luego el cliente mismo la recordara y hara el tramite mas rapido
session.login('USER','PASSWORD')   #se nos solicitara nuestro usuario de spotify, ya que sin esta funcion no nos permitiria la reproducion de musica
while True:
    session.process_events()
    print "Conectando......."
    if session.connection.state == 1:  # cuando se cumpla dicha condicion, efectivamente estaremos conectados y listos para usar el cliente
        break
    
spotipy = spotipy.Spotify()
print "\n\n","-----------------------------------------------------------------","\n\n"
cancion=raw_input("Ingresa el nombre de la cancion que quieres escuchar: ")     # se crea un input cuya funcion es obtener el nombre de la cancion que se quiere escuchar
print "\n\n"
results = spotipy.search(cancion, limit=10)   # en este caso se implemento que la busqueda nos entregase solo 10 canciones, obviamente son las con mayores coincidencias                                                
songs = {}                                    # ordenadas de modo mejor a peor opcion
cont = 1
for i in results['tracks']['items']:
    on = unicodedata.normalize("NFKD",i['name']).encode("ascii","ignore")+" de "+ unicodedata.normalize("NFKD",i["artists"][0]["name"]).encode("ascii","ignore")
    songs[str(cont)] = {"play_song":str(i["uri"]),"name":on,"image":i['album']['images'][1]['url'],"ID":i['name']}
    print str(cont)+".-"+ i['name'],"de",i["artists"][0]["name"] # en esta parte del codigo mas que nada se obtiene informacion valiosa como el nombre
    cont += 1                                                     # de la cancion, del artista y su cover de album, se almacena todo en un diccionario 
    
play = raw_input("\n\n¿Cual Quieres escuchar?: ")    # este input nuevamente nos preguntara cual cancion queremos escuchar, rellenaremos este campo con el numero de la cancion
audio = spotify.AlsaSink(session)                    # para poder escuchar las canciones se utiliza ALSA, es un software de sonido presente en sistemas linux
track = session.get_track(songs[play]["play_song"])
track.load()
session.player.load(track)
session.player.play()     # se procede con la reproducion
print "\n\n","########## Estas escuchando ",songs[play]["name"],"##########"