Exemplo n.º 1
0
def main():
    args = my_arg_parser()

    parent_dir = os.path.abspath(os.pardir)
    config_file = os.path.join(parent_dir, "config.ini")
    config = ConfigParser.ConfigParser()
    config.read(config_file)

    spotify_client_id = config.get('spotify', 'client_id')
    print "spotify_client_id"
    spotify_client_secret = config.get('spotify', 'client_secret')
    print "spotify_client_secret"
    spotify_token_url = config.get('spotify', 'token_url')
    print "spotify_token_url"
    token = sp.get_spotify_oauth_token(spotify_client_id, spotify_client_secret, spotify_token_url)
    print "get get_spotify_oauth_token"
    playlists = sp.get_user_playlists(token, args.username)
    print "get_user_playlists"
    track_urls = sp.get_playlist_track_urls(playlists, args.username)
    print "get_playlist_track_urls"
    track_data = sp.get_tracks(track_urls, token)
    print "get_tracks"
    parsed_data, json_data = sp.parse_track_data(track_data)
    print "parse_track_data"
    output_file = "track_data.json"
    output = os.path.abspath(os.path.realpath(output_file))

    sp.save_json_data(json_data, output)
    print "save_json_data"
    sorted_data = sp.sort_track_data(parsed_data)
    print "sort_track_data"
    sp.create_bar_chart(sorted_data)
    print "create_bar_chart"
Exemplo n.º 2
0
def main():
    args = parse_args()

    # load your config.ini file
    parent_dir = os.path.dirname(os.path.dirname(__file__))
    config_file = os.path.join(parent_dir, "config.ini")
    config = ConfigParser.ConfigParser()
    config.read(config_file)

    # parse out spotify configuration
    spotify_client_id = config.get('spotify', 'client_id')
    spotify_client_secret = config.get('spotify', 'client_secret')
    spotify_token_url = config.get('spotify', 'token_url')

    # Get an OAuth token from Spotify
    token = sp.get_spotify_oauth_token(spotify_client_id,
                                       spotify_client_secret,
                                       spotify_token_url)

    # get the desired user's list of playlists
    playlists = sp.get_user_playlists(token, args.username)

    # parse out the tracks URL for each playlist
    track_urls = sp.get_playlist_track_urls(playlists, args.username)

    # request track data from the tracks URLs
    track_data = sp.get_tracks(track_urls, token)

    # parse track data into parsed_data and json_data
    parsed_data, json_data = sp.parse_track_data(track_data)

    # save the json_data for future use with EchoNest
    output_file_name = config.get('spotify', 'output_file_name')
    output_file = os.path.abspath(os.path.realpath(output_file_name))
    sp.save_json_data(json_data, output_file)

    # sort the parsed_data of tracks into their appropriate buckets
    sorted_data = sp.sort_track_data(parsed_data)

    # create a bar chart with the sorted_data!
    sp.create_bar_chart(sorted_data)
Exemplo n.º 3
0
def index():
    user = {'nickname': 'Miguel'}  # fake user
    if 'access_token' not in session:

        return render_template('index.html',
                           title='Maddipy',
                           user=user)
    else:
        user_info = spotify.get_user_info()
        session['user_id'] = user_info['id']
        session['display_name'] = user_info['display_name'] \
                                    if user_info['display_name'] else user_info['id']

        session['playlists'] = spotify.get_user_playlists()
        names = [playlist['name'] for playlist in session['playlists']]

        return render_template('home.html',
                                title='Maddipy',
                                display_name= session['display_name'],
                                playlists= session['playlists'],
                                names=names)
Exemplo n.º 4
0
def main():
    args = parse_args()

    if args.debug:
        log.setLevel(logging.DEBUG)
    else:
        log.setLevel(logging.INFO)

    # Config Shit
    parent_dir = os.path.dirname(os.path.dirname(__file__))
    config_file = os.path.join(parent_dir, "config.ini")
    config = ConfigParser.ConfigParser()
    config.read(config_file)

    echonest_api_key = config.get('echonest', 'api_key')
    spotify_client_id = config.get('spotify', 'client_id')
    spotify_client_secret = config.get('spotify', 'client_secret')
    spotify_token_url = config.get('spotify', 'token_url')
    github_oauth = config.get('github', 'oauth')
    artist_data_file = config.get('echonest', 'output_file_name')
    output_file_name = config.get('echonest', 'output_file_name')
    json_input = config.get('spotify', 'output_file_name')
    artist_json = json.load(open(artist_data_file, 'r'))

    # Spotify API
    log.debug("Getting a Spotify OAuth Token with your client ID")
    token = sp.get_spotify_oauth_token(spotify_client_id,
                                       spotify_client_secret,
                                       spotify_token_url)

    log.debug("Getting public playlists for {0}".format(args.spotify_user))
    playlists = sp.get_user_playlists(token, args.spotify_user)

    log.debug("Parsing out track URLs from each playlist")
    track_urls = sp.get_playlist_track_urls(playlists, args.spotify_user)
    log.debug("Parsed tracks from {0} playlists.".format(len(track_urls)))

    log.debug("Fetching track data for each track URL.")
    track_data = sp.get_tracks(track_urls, token)
    log.debug("Received track data on {0} playlists.".format(len(track_data)))

    log.debug("Parsing track data, and creating & saving a JSON file.")
    parsed_data, json_data = sp.parse_track_data(track_data)

    output_file_name = config.get('spotify', 'output_file_name')
    output_file = os.path.abspath(os.path.realpath(output_file_name))
    sp.save_json_data(json_data, output_file)
    log.debug("Saved the JSON file at: '{0}'".format(output_file))

    log.debug("Sorting parsed track data.")
    sorted_data = sp.sort_track_data(parsed_data)

    log.debug("Attempting to create an awesome bar chart...")
    sp.create_bar_chart(sorted_data)
    current_dir = os.path.abspath(os.path.dirname(__file__))
    log.debug("Chart saved as 'Music Timeline.png' in '{0}'.".format(
              current_dir))
    log.debug("Finished getting playlists from Spotify!")

    # EchoNest API
    en = pyen.Pyen(echonest_api_key)

    playlist_json = json.load(open(json_input, "r"))

    unique_artists = ec.deduplicate_artists(playlist_json)

    log.debug("Fetching artist information for {0} artists.".format(
              len(unique_artists)))
    log.debug("Perhaps go get some coffee, or a have a bathroom break,"
              "this may take a while depending on how many artists "
              "there are :D.")
    artists = ec.get_artists_information(en, unique_artists)

    log.debug("Creating JSON output of artist information.")
    json_output = ec.create_json(artists)

    output_file = os.path.abspath(os.path.realpath(output_file_name))

    log.debug("Saving JSON output to {0}.".format(output_file))
    ec.save_json(json_output, output_file)

    # GitHub API
    log.debug("Creating a GeoJSON file with artist info from {0}".format(
              artist_data_file))
    geojson_file = gh.create_geojson(artist_json)

    if github_oauth:
        log.debug("Logging you into GitHub...")
        try:
            gh_auth = gh.login_github(github_oauth)
            log.debug("Successfully logged into GitHub! \n"
                      "Posting the gist to your Account.")
        except gh.GithubError:
            gh_auth = None
            log.info("Could not log you in. Will post your Gist anonymously.")
    else:
        gh_auth = None

    gist_url = gh.post_gist_github(geojson_file, gh_auth, args.gist_desc)

    log.info("Your gist has been posted! Navigating you to: {0}".format(
             gist_url))
    webbrowser.open(gist_url)
Exemplo n.º 5
0
def main():
    args = parse_args()

    # load your config.ini file
    parent_dir = os.path.dirname(os.path.dirname(__file__))
    config_file = os.path.join(parent_dir, "config.ini")
    config = ConfigParser.ConfigParser()
    config.read(config_file)

    # parse out spotify configuration
    spotify_client_id = config.get('spotify', 'client_id')
    spotify_client_secret = config.get('spotify', 'client_secret')
    spotify_token_url = config.get('spotify', 'token_url')

    # Get an OAuth token from Spotify
    token = sp.get_spotify_oauth_token(spotify_client_id,
                                       spotify_client_secret,
                                       spotify_token_url)

    # get the desired user's list of playlists
    playlists = sp.get_user_playlists(token, args.username)

    # parse out the tracks URL for each playlist
    track_urls = sp.get_playlist_track_urls(playlists, args.username)

    # request track data from the tracks URLs
    track_data = sp.get_tracks(track_urls, token)

    # parse track data into parsed_data and json_data
    parsed_data, json_data = sp.parse_track_data(track_data)

    # save the json_data for future use with EchoNest
    output_file_name = config.get('spotify', 'output_file_name')
    output_file = os.path.abspath(os.path.realpath(output_file_name))
    sp.save_json_data(json_data, output_file)

    # sort the parsed_data of tracks into their appropriate buckets
    sorted_data = sp.sort_track_data(parsed_data)

    # create a bar chart with the sorted_data!
    sp.create_bar_chart(sorted_data)

    # EchoNest API

    # Grab your EchoNest API key from your config
    echonest_api_key = config.get('echonest', 'api_key')

    # Grab where you saved the track data from Spotify
    output_file_name = config.get('echonest', 'output_file_name')
    json_input = config.get('spotify', 'output_file_name')

    # instantiate the EchoNest APY
    en = pyen.Pyen(echonest_api_key)

    # Open the track data we saved from Spotify
    playlist_json = json.load(open(json_input, "r"))

    # Deduplicate the artists
    unique_artists = ec.deduplicate_artists(playlist_json)

    # Get our artist information
    artists = ec.get_artists_information(en, unique_artists)

    # Create a JSON-like object with our artist information
    json_output = ec.create_json(artists)

    # Define where the JSON will be saved based off of our config
    output_file = os.path.abspath(os.path.realpath(output_file_name))

    # Save the data into a JSON file
    ec.save_json(json_output, output_file)
Exemplo n.º 6
0
def main():
    args = parse_args()

    log = logging.getLogger('pyladies_api')
    stream = logging.StreamHandler()
    log.addHandler(stream)

    if args.debug:
        log.setLevel(logging.DEBUG)
    else:
        log.setLevel(logging.INFO)

    # load your config.ini file
    parent_dir = os.path.dirname(os.path.dirname(__file__))
    config_file = os.path.join(parent_dir, "config.ini")
    config = ConfigParser.ConfigParser()
    config.read(config_file)

    # parse out spotify configuration
    spotify_client_id = config.get('spotify', 'client_id')
    spotify_client_secret = config.get('spotify', 'client_secret')
    spotify_token_url = config.get('spotify', 'token_url')

    # Get an OAuth token from Spotify
    token = sp.get_spotify_oauth_token(spotify_client_id,
                                       spotify_client_secret,
                                       spotify_token_url)

    # get the desired user's list of playlists
    playlists = sp.get_user_playlists(token, args.username)

    # parse out the tracks URL for each playlist
    track_urls = sp.get_playlist_track_urls(playlists, args.username)

    # request track data from the tracks URLs
    track_data = sp.get_tracks(track_urls, token)

    # parse track data into parsed_data and json_data
    parsed_data, json_data = sp.parse_track_data(track_data)

    # save the json_data for future use with EchoNest
    output_file_name = config.get('spotify', 'output_file_name')
    output_file = os.path.abspath(os.path.realpath(output_file_name))
    sp.save_json_data(json_data, output_file)

    # sort the parsed_data of tracks into their appropriate buckets
    sorted_data = sp.sort_track_data(parsed_data)

    # create a bar chart with the sorted_data!
    sp.create_bar_chart(sorted_data)

    # EchoNest API

    # Grab your EchoNest API key from your config
    echonest_api_key = config.get('echonest', 'api_key')

    # Grab where you saved the track data from Spotify
    output_file_name = config.get('echonest', 'output_file_name')
    json_input = config.get('spotify', 'output_file_name')

    # instantiate the EchoNest APY
    en = pyen.Pyen(echonest_api_key)

    # Open the track data we saved from Spotify
    playlist_json = json.load(open(json_input, "r"))

    # Deduplicate the artists
    unique_artists = ec.deduplicate_artists(playlist_json)

    # Get our artist information
    artists = ec.get_artists_information(en, unique_artists)

    # Create a JSON-like object with our artist information
    json_output = ec.create_json(artists)

    # Define where the JSON will be saved based off of our config
    output_file = os.path.abspath(os.path.realpath(output_file_name))

    # Save the data into a JSON file
    ec.save_json(json_output, output_file)

    ###
    # GitHub API
    ###

    # Load GitHub configuration
    github_oauth = config.get('github', 'oauth')

    # Grab the file that we saved with echonest earlier
    artist_data_file = config.get('echonest', 'output_file_name')

    # load this file so we can read it
    artist_json = json.load(open(artist_data_file, 'r'))

    # Create a GeoJSON-like object with our artist information
    geojson_output = gh.create_geojson(artist_json)

    # Either log into GitHub if you do have a GitHub account
    if github_oauth:
        try:
            gh_auth = gh.login_github(github_oauth)
        except gh.GithubError:
            gh_auth = None

    # Or if no account, then set the auth to None
    else:
        gh_auth = None

    # POST the GeoJSON to GitHub
    gist_url = gh.post_gist_github(geojson_output, gh_auth, args.gist_desc)

    # Open the default system browser to the gist URL that we just created
    webbrowser.open(gist_url)
Exemplo n.º 7
0
def lambda_handler(event, context):

    connection_id = event["requestContext"].get("connectionId")
    body = event["body"]
    body = json.loads(
        body
    )  # if body is not None else '{"Error": "Need to set this default value"}')
    domain = event.get('requestContext', {}).get('domainName')
    stage = event.get('requestContext', {}).get('stage')
    apig_management_client = boto3.client(
        'apigatewaymanagementapi', endpoint_url=f'https://{domain}/{stage}')

    status_code = 200

    if body['requestType'] == 'playlists':
        playlists = get_user_playlists()
        message = f"{playlists}".encode('utf-8')
        logger.info(f"playlist message: {message}")

        try:
            send_response = apig_management_client.post_to_connection(
                Data=message, ConnectionId=connection_id)
            logger.info(
                f"Posted message to connection {connection_id}, got response {send_response}"
            )
        except ClientError:
            logger.exception(f"Couldn't post to connection {connection_id}")
            status_code = 450
        except apig_management_client.exceptions.GoneException:
            logger.info(f"Connection {connection_id} is gone, removing.")
            status_code = 460

    elif body['requestType'] == 'lyrics':
        # TODO: abstract this code out elsewhere, clean it up
        # currently solving for ONE playlist given, as a string (PLAYLIST_NAME: ID)
        playlists_ = re.findall(r'(.+):\ (\w+)', body['playlists'])
        logger.info(f"playlists_ = {playlists_}")
        playlist = Playlist(playlists_[0][0], playlists_[0][1])
        set_of_songs = get_song_set([playlist])

        message = ""
        genius_songs = get_songs_from_lyrics(body['lyrics'])
        for song in genius_songs:
            if song in set_of_songs:
                message = f"Found match! {song}".encode('utf-8')

        if message == "":
            message = "No matches found".encode('utf-8')
        logger.info(f"lyric match message: {message}")

        try:
            send_response = apig_management_client.post_to_connection(
                Data=message, ConnectionId=connection_id)
            logger.info(
                f"Posted message to connection {connection_id}, got response {send_response}"
            )
        except ClientError:
            logger.exception(f"Couldn't post to connection {connection_id}")
            status_code = 450
        except apig_management_client.exceptions.GoneException:
            logger.info(f"Connection {connection_id} is gone, removing.")
            status_code = 460

    return status_code
Exemplo n.º 8
0
from spotify import get_user_playlists, get_playlists_songs, add_song_to_queue
from genius import get_songs_from_lyrics
from typing import Sequence
from song import Song
from playlist import Playlist
import sys
# import requests_cache
import functools

# requests_cache.install_cache('data_collector_cache', backend='sqlite', expire_after=99999999999)

MY_PLAYLISTS = get_user_playlists()
PLAYLIST_DICT = {}
for i, playlist in enumerate(MY_PLAYLISTS):
    PLAYLIST_DICT[i] = playlist


@functools.lru_cache(maxsize=1000)
def get_song_set(playlists: Sequence[Playlist]) -> Sequence[Song]:
    all_songs = []
    for pl in playlists:
        all_songs.extend(get_playlists_songs(pl))
    return set(all_songs)


def make_artist_set(songs: Sequence[Song]) -> Sequence[str]:
    return set([s.artist for s in songs])


PLAYLIST_SONGS = get_song_set([PLAYLIST_DICT[60], PLAYLIST_DICT[15]])