Ejemplo n.º 1
0
async def export():
    # TODO: Implement JS logic to issue error
    validate = auth.validateAccessToken()
    if validate:
        return await redirect(validate)

    genre = (await request.get_json())['genre']
    access_token = session['access_token']
    sp = spotify.Spotify(access_token)

    async with aiohttp.ClientSession(json_serialize=ujson) as sess:
        # TODO: User sets the genre name
        playlist_id = await create_playlist(sp, sess, genre)

        tracks_to_export = redis_cache.get_user_genre_tracks(
            access_token, genre)
        # TODO: Sort on popularity
        # TODO: Remove hotfix
        tracks_to_export = [
            "spotify:track:" + track for track in tracks_to_export
        ]
        # TODO: retry logic in this function? display error if false
        await add_tracks_to_playlist(sp, sess, playlist_id, tracks_to_export)

    return genre
Ejemplo n.º 2
0
    def input(self, char):
        logging.debug("input: " + char)
        # OFF
        if self.state == "off":
            if char == "w":
                self.webradio = webradio.WebRadio(self.args)
                self.state = "webradio"
            elif char == "s":
                self.spotify = spotify.Spotify(self.args)
                self.state = "spotify"
            elif char == "x":
                logging.info("Stopped.")

        # WEBRADIO
        elif self.state == "webradio":
            if char == "x":
                self.webradio.stop()
                self.state = "off"
            elif char == ">":
                self.webradio.next()
            elif char == "<":
                self.webradio.prev()
            elif char == " ":
                self.webradio.play_pause()
            elif char == "l":
                self.webradio.list_stations()

        # SPOTIFY
        elif self.state == "spotify":
            if char == "x":
                self.spotify.stop()
                self.state = "off"

        logging.debug("state: " + self.state)
Ejemplo n.º 3
0
async def playlist(genre):
    validate = auth.validateAccessToken()
    if validate:
        return await redirect(validate)

    access_token = session['access_token']
    songs = redis_cache.get_user_genre_tracks(access_token, genre)
    song_info_map = [
        redis_cache.get_spotify_track_name(t_id) for t_id in songs
    ]
    sorted_song_info_map = sorted(song_info_map,
                                  key=lambda s: int(s['popularity']),
                                  reverse=True)

    sp = spotify.Spotify(access_token)
    d_id, devices = await player.get_device_info(sp)

    # extract artists back to strings
    for song in sorted_song_info_map:
        song['artists'] = ', '.join(ujson.loads(song['artists']))

    return await render_template('playlist_list.html',
                                 song_info_map=sorted_song_info_map,
                                 genre=genre,
                                 access_token=access_token,
                                 d_id=d_id,
                                 devices=devices)
Ejemplo n.º 4
0
async def load_songs_counts():
    access_token = await websocket.receive()
    # TODO: Authentication quart-auth ?

    try:
        sp = spotify.Spotify(access_token)
        async with aiohttp.ClientSession(json_serialize=ujson) as sess:
            tracks = await sp.current_user_saved_tracks(50, 0, sess)
            # total = result['total']  # TODO: Testing, currently capping at 100
            total = 200
            log.info(f"User has a total of {total} tracks")
            await websocket.send(str(total))

            await extract_tracks(sp, sess, tracks)

            loop = asyncio.get_event_loop()
            asyncio_tasks = []
            for offset in range(50, total, 50):
                tracks = await sp.current_user_saved_tracks(50, offset, sess)
                asyncio_tasks.append(
                    loop.create_task(extract_tracks(sp, sess, tracks)))

            # collect remaining artists and album ids to be called
            res = await asyncio.gather(*asyncio_tasks)
            res = reduce(
                lambda x, y:
                (x[0] + y[0], x[1] + y[1], x[2] + y[2], x[3] + y[3]), res)

            # update remaining artist and album genres
            await asyncio.gather(*[
                loop.create_task(
                    batch_update_artist_genres(sp, sess, res[0][i:i + 49],
                                               res[1][i:i + 49]))
                for i in range(0, len(res[0]), 49)
            ])

            await asyncio.gather(*[
                loop.create_task(
                    batch_update_album_genres(sp, sess, res[2][i:i + 19],
                                              res[3][i:i + 19]))
                for i in range(0, len(res[0]), 49)
            ])

        # map user's saved tracks to redis
        # TODO: maybe have async gather on genre:len(tids) to eliminate SCARD overhead
        redis_cache.set_user_genre_track_count(access_token)

        await websocket.send("STOP")
        # return redirect(url_for('spotify_analytics'))

    except asyncio.CancelledError:
        # TODO: Handle disconnect
        log.debug("CLIENT CLOSED")
        raise
Ejemplo n.º 5
0
def genderfm(access_token):
    spotify_service = spotify.Spotify(access_token)
    artists = spotify_service.top_artists(time_range='long_term')
    artists_with_gender = add_gender(artists)
    total_score = 0.0
    total_affinity = 0
    res = {"artists": [], "score": 0.5}
    for i, artist in enumerate(artists_with_gender):
        score = gender_score(artist['gender'])
        if score is not None:
            total_score += score * int(artist['affinity'])
            total_affinity += int(artist['affinity'])
        print artist['name'], artist['affinity'], artist[
            'gender_provider'], artist['gender']
        res["artists"].append(to_genderfm_artist(artist))
    res["score"] = round((total_score / total_affinity) * 100, 1)
    return res
Ejemplo n.º 6
0
def init_globals(keynum):
    global downloaded_songs, downloaded_songs_lock, started_songs, started_songs_lock, error_file_lock, url_file_lock, youtube, client_id, client_secret
    global youtube_lock
    global spoti
    global longsongs_file_lock

    global DEBUGG
    global VERBOSE
    global OUT_FOLDER

    downloaded_songs_lock = threading.Lock()
    started_songs_lock = threading.Lock()
    error_file_lock = threading.Lock()
    url_file_lock = threading.Lock()
    longsongs_file_lock = threading.Lock()
    youtube_lock = threading.Lock()
    downloaded_songs = 0
    started_songs = 0
    client_id = 'c6c3f6355e3349ce8160f0f2504e442b'
    client_secret = '2da4af43872a462ab652f579aa4b9d04'

    # Parse arguments into global variables
    DEBUGG, VERBOSE, OUT_FOLDER = helper.argparser()

    #! Store keys in file which doesnt go to github so my keys are not stolen
    # Use 1st key first time, and if we need to download more stuff change keynum to 2 so we use the second key
    ytb_key = helper.read_ytb_key('keys.txt', keynum=keynum)
    youtube = build('youtube', 'v3', developerKey=ytb_key)

    # Get spotify credentials through OAuth 2.0
    spoti = spotify.Spotify(client_id, client_secret)
    spoti.get_auth_code()
    spoti.get_tokens()

    # * Delete failed_songs file and if exist at the beginning
    if os.path.exists('failed_songs.txt'):
        os.remove('failed_songs.txt')
    if os.path.exists('long_songs.txt'):
        os.remove('long_songs.txt')
Ejemplo n.º 7
0
    def __init__(self, bot):
        self.dictionary = {}
        self.bot = bot
        self.log = logging_manager.LoggingManager()
        self.spotify = spotify.Spotify()
        self.youtube = youtube.Youtube()
        self.lastfm = lastfm.LastFM()
        self.mongo = mongo.Mongo()
        bot.remove_command("help")
        self.log.debug("[Startup]: Initializing Music Module . . .")

        def generate_key(length):
            letters = string.ascii_letters
            response = ""
            for a in range(0, length):
                response += random.choice(letters)
            return response

        restart_key = generate_key(64)
        asyncio.run_coroutine_threadsafe(self.mongo.set_restart_key(restart_key), self.bot.loop)

        if not discord.opus.is_loaded():
            discord.opus.load_opus("/usr/lib/libopus.so")
Ejemplo n.º 8
0
from config_updater import update_config
from time import sleep
import telebot as tb
import configparser
import spotify
import logging
import hashlib

config = configparser.ConfigParser()
config.read('./config.ini')
bot = tb.TeleBot(config['bot']['token'], threaded=False)
spotify_client = spotify.Spotify()
track_data = {}
search_state = config['bot']['search_state']
bot_logger = logging.getLogger(config['logger']['title'])
logging.basicConfig(filename=config['logger']['filename'],
                    level=logging.INFO,
                    format=config['logger']['text_format'],
                    datefmt=config['logger']['date_format'])


@bot.message_handler(commands=['start'])
def welcome(message):
    bot.send_message(
        chat_id=message.chat.id,
        text='Привет.\nПока что я умею искать только артистов и треки',
        reply_markup=spotify_client.make_search_button())


@bot.message_handler(commands=['log'])
def send_log(message):
Ejemplo n.º 9
0
def create_a_playlist(reddit_url, playlist_title):
    reddit_list = reddit.RedditAPI(reddit_url)
    titles = reddit_list.get_titles()

    spot = spotify.Spotify(titles, playlist_title)
    spot.playlist_creation()
Ejemplo n.º 10
0
    def get_spotify():
        if 'spotify' not in g:
            g.spotify = spotify.Spotify(app.config["CLIENT_ID"],
                                        app.config["CLIENT_SECRET"])

        return g.spotify
import os
import spotify
import youtube

spotify_oauth_token = os.environ.get("SPOTIFY_OAUTH_TOKEN")
spotify_user_id = os.environ.get("SPOTIFY_USER_ID")

if __name__ == "__main__":
    # intializing an instance of the youtube and spotify classes
    yt = youtube.Youtube()
    spotify = spotify.Spotify(spotify_user_id, spotify_oauth_token)

    yt_playlist_id = yt.get_playlist_id("Spotify")
    unfiltered_song_list = yt.get_song_list(yt_playlist_id)
    spotify_playlist_id = spotify.create_playlist("From Youtube")
    filtered_songs = spotify.filter_titles(unfiltered_song_list)
    # adding each song to the playlist
    for song in filtered_songs:
        track_uri = spotify.get_spotify_song_uri(song)
        # if a search result came back from the spotify API
        if track_uri != None:
            spotify.add_song_to_playlist(spotify_playlist_id, track_uri)
            print("Added {song} to the playlist".format(song=song))
Ejemplo n.º 12
0
def process(path, outdir, regex, sampling):
    if not os.path.exists(outdir):
        os.makedirs(outdir)

    global state

    # Get a file that should exist in the outdir
    # this file is used for saving state between multiple
    # runs of this script
    state, state_file = get_state_and_file(outdir)

    s = spotify.Spotify()
    s.authenticate()

    entry = FileEntry(path, None)
    entry.build(regex=regex)

    for file in entry.get_files():
        digest = hashlib.md5(open(file.path(), 'rb').read()).hexdigest()
        if state.get(digest, None) is not None:
            continue

        try:
            data = mutagenwrapper.read_tags(file.path())
            artist = data.get('artist')[0]
            title = data.get('title')[0]
            if artist == '' or title == '':
                logger.error('Failed on file {}'.format(file.path()))
                continue
            print '{} - {}'.format(artist, title)
            params = {
                'q': 'artist:{} title:{}'.format(artist, title),
                'type': 'track',
                'limit': 1
            }
        except Exception, e:
            tb = traceback.format_exc()
            print tb

        try:
            search = s.search(params)
            item0 = search['tracks']['items'][0]
            trackid = item0['id']
            artist = item0['artists'][0]['name']
            track = item0['name']

            features = s.audio_features(trackid)
            analysis = s.audio_analysis(trackid)

            features['ub_source_file'] = os.path.abspath(file.path())
            analysis['ub_source_file'] = os.path.abspath(file.path())

            base = '{} - {}'.format(artist, track)
            # XXX: Hack..handle AC/DC
            base = base.replace('/', '_')
            # Now join with outdir
            base = os.path.join(outdir, base)

            features_file = '{}.features.gz'.format(base)
            analysis_file = '{}.analysis.gz'.format(base)

            with pycommons.open_file(features_file, 'wb', True) as f:
                f.write(json.dumps(features))
            with pycommons.open_file(analysis_file, 'wb', True) as f:
                f.write(json.dumps(analysis))

            state[digest] = True
        except Exception, e:
            logger.error("Could not process file {}: {}".format(
                file.path(), e))