Esempio n. 1
0
def populateSongs(session, album_db_obj, album):
    """Populates the song database table with data from the Spotify API.

    Keyword arguments:
    session -- the database session.
    album_db_obj -- the album database object.
    album -- the album object containing Spotify data.
    """
    song_objects = []

    # Populate album information based on the album search.
    for track in album['tracks']['items']:
        track_info = sp.track(track['uri'])
        track_features = sp.audio_features(track['id'])[0]

        song = Song(uri=track_info['uri'],
                    track_number=track_info['track_number'],
                    name=track_info['name'],
                    popularity=track_info['popularity'],
                    duration=track_info['duration_ms'],
                    explicit=track_info['explicit'],
                    danceability=track_features['danceability'],
                    tempo=track_features['tempo'],
                    energy=track_features['energy'],
                    instrumentalness=track_features['instrumentalness'],
                    time_signature=track_features['time_signature'],
                    valence=track_features['valence'],
                    album_id=album_db_obj.id,
                    album=album_db_obj)
        song_objects.append(song)

    session.add_all(song_objects)
    session.commit()
Esempio n. 2
0
def load_songs(song_filename):
    """Load songs from songs.txt into database."""

    print("Songs")

    for i, row in enumerate(open(song_filename)):
        row = row.rstrip()
        song_id, song_title, song_release_date_str, song_release_year_str, song_release_month_str, song_release_day_str, apple_music_player_url = row.split(
            "|")

        if not song_release_year_str or song_release_year_str in (
                'None', 'None"', '') or len(song_release_year_str) != 4:
            song_release_year_str = None

        if not song_release_month_str or song_release_month_str in ('None',
                                                                    'None"',
                                                                    ''):
            song_release_month_str = None
        else:
            if len(song_release_month_str) == 1:
                song_release_month_str = "0" + song_release_month_str

        if not song_release_day_str or song_release_day_str in ('None',
                                                                'None"', ''):
            song_release_day_str = None
        else:
            if len(song_release_day_str) == 1:
                song_release_day_str = "0" + song_release_day_str

        if song_release_year_str and song_release_month_str and song_release_day_str:
            song_release_date_str = " ".join([
                song_release_year_str, song_release_month_str,
                song_release_day_str
            ])
            song_release_date = datetime.datetime.strptime(
                song_release_date_str, "%Y %m %d")

        song = Song(song_id=song_id,
                    song_title=song_title,
                    song_release_year=song_release_year_str,
                    song_release_date=song_release_date,
                    apple_music_player_url=apple_music_player_url)

        db.session.add(song)

        if i % 1000 == 0:
            print(i)

            # An optimization: if commit after every add, the database
            # will do a lot of work committing each record. However,
            # waiting until the end may be quite the load on computers with
            # smaller amounts of memory; it might thrash around. Committing
            # every 1,000th add is a good balance.
            db.session.commit()

    db.session.commit()
Esempio n. 3
0
def insert_song(type: str, meta: dict):
    if (type=='song'):
        temp = Song(meta)
    elif (type=='podcast'):
        temp = Podcast(meta)
    elif (type=='audiobook'):
        temp = AudioBook(meta)

    id = db.insert_file("song", temp.convert_dict())
    return {"id": id}
Esempio n. 4
0
def add_songs_to_db(artist, db_setlist_list):
    """Add songs from list of strings to db with primary_artist id."""
    if db_setlist_list:
        for song in db_setlist_list:
            try:
                artist.songs.append(Song(song_name=song))
                db.session.commit()
            except IntegrityError:
                db.session.rollback()
                continue
Esempio n. 5
0
def playlist_add_confirmed():
    is_uploaded = yt_re.search(request.form['uri']) is None

    # we'll clean up duplicates manually
    song = Song(uri=request.form['uri'], title=request.form['title'], artist=request.form['artist'])
    song.submitter = request.form['submitter']
    song.is_uploaded = is_uploaded
    song.created = datetime.datetime.now()

    db.session.add(song)
    db.session.commit()
    return render_template('playlist/add_confirmed.html', song=song)
Esempio n. 6
0
def load_songs(song_list):
    """Load songs from Guitar Party API into database."""
    print "Songs"

    for item in song_list:

        if Song.query.filter_by(song_id=item['id']).first() == None:

            song = Song(song_id=item['id'],
                        title=item['title'],
                        body=item['body'],
                        body_chords_html=item['body_chords_html'],
                        permalink=item['permalink'])

            db.session.add(song)

    db.session.commit()
Esempio n. 7
0
def add_song(path):
    getcontext().prec = 3
    tag = tiny.get(path)
    artist = session.query(Artist).filter_by(name=tag.artist).first()
    if artist == None:
        artist = Artist(name=tag.artist)
        session.add(artist)
    album = session.query(Album).filter_by(name=tag.album).first()
    if album == None:
        album = Album(name=tag.album, num_songs=0, artist=artist)
        session.add(album)

    album.num_songs += 1
    duration = Decimal(tag.duration) / Decimal(60)
    song = Song(name=tag.title,
                release_date=tag.year,
                genre=tag.genre,
                length=duration,
                album=album,
                path=path)
    session.add(song)
    song.artists.append(artist)
    session.commit()
Esempio n. 8
0
def create_song(song_title, song_uri, tempo, valence, danceability, energy,
                loudness, acousticness, speechiness, song_artist):
    """Creates a Song and adds it to the database."""

    song = Song(song_title=song_title,
                song_uri=song_uri,
                tempo=tempo,
                valence=valence,
                danceability=danceability,
                energy=energy,
                loudness=loudness,
                acousticness=acousticness,
                speechiness=speechiness,
                song_artist=song_artist)

    # makes sure the song isn't already in the db
    if get_song_id(song_uri) == None:

        db.session.add(song)
        db.session.commit()

        return song
    else:
        return song
Esempio n. 9
0
def generate_playlist():

    original_spotify_info = spotify.base_playlist(
        spotify.generate_token(), session["genre"].lower(),
        session["minimum_danceability"], session["maximum_danceability"])

    clean_array = []

    index = 0
    for track in original_spotify_info["tracks"]:

        if track["preview_url"] is not None:
            clean_array.append(track)
        index += 1

    spotify_info = {"tracks": clean_array}

    if len(spotify_info.get("tracks")) <= 0:
        flash(
            "Change the search parameters of danceability. No playlist was generated."
        )
        return redirect("/create")
    else:

        playlist = Playlist(
            user_id=session["user_id"],
            playlist_image=spotify_info["tracks"][0]["album"]["images"][1]
            ["url"],
            playlist_genre=session["genre"].lower(),
            playlist_mindanceability=session["minimum_danceability"],
            playlist_maxdanceability=session["maximum_danceability"])
        db.session.add(playlist)
        db.session.commit()

        #store songs into Song database and song-playlist data into SongPlaylist database
        for track in spotify_info["tracks"]:
            #if Song database is empty, add generated song as new song in the database
            if len(db.session.query(Song).all()) <= 0:
                song = Song(
                    track_id=track["id"],
                    track_title=track["name"],
                    artist=[artist["name"] for artist in track["artists"]])
                db.session.add(song)
                db.session.commit()
        #if a song(s) exists in the database, check to see if there is a match with generated song
        #and existing song(s) match. If there is no match, add generated song as new song in the database.
        #Both if statements check to make sure new songs that are added into database do not already
        #exist in the database.
            if len(
                    db.session.query(Song).filter(
                        Song.track_id == track["id"]).all()) <= 0:
                song = Song(
                    track_id=track["id"],
                    track_title=track["name"],
                    artist=[artist["name"] for artist in track["artists"]])
                db.session.add(song)
                db.session.commit()
            songplaylist = SongPlaylist(track_id=track["id"],
                                        playlist_id=playlist.playlist_id)
            db.session.add(songplaylist)
            db.session.commit()

    #reveal newly generated playlist on generate_playlist.html page based on stored session from user input above

    #create json format that in the form that Amplitude.js can read
    spotify_info_list = []
    for track in spotify_info["tracks"]:
        spotify_info_dict = {}
        millis = int(track["duration_ms"])
        minutes = millis / (1000 * 60)
        minutes = int(minutes)
        seconds = (millis % (1000 * 60)) / 1000
        seconds = int(seconds)
        if seconds == 0:
            seconds = "00"
        if seconds == 1:
            seconds = "01"
        if seconds == 2:
            seconds = "02"
        if seconds == 3:
            seconds = "03"
        if seconds == 4:
            seconds = "04"
        if seconds == 5:
            seconds = "05"
        if seconds == 6:
            seconds = "06"
        if seconds == 7:
            seconds = "07"
        if seconds == 8:
            seconds = "08"
        if seconds == 9:
            seconds = "09"

        track["duration_ms"] = f'{minutes}:{seconds}'

        spotify_info_dict["name"] = track["name"]
        spotify_info_dict["artist"] = [
            f' {artist["name"]}' for artist in track["artists"]
        ]
        spotify_info_dict["album"] = track["album"]["name"]
        spotify_info_dict["url"] = track["preview_url"]
        spotify_info_dict["cover_art_url"] = track["album"]["images"][0]["url"]

        spotify_info_list.append(spotify_info_dict)

    fin_spotify_dict = {}
    fin_spotify_dict["songs"] = spotify_info_list

    return render_template("amplitude_generate_playlist.html",
                           spotify_info=spotify_info,
                           fin_spotify_dict=fin_spotify_dict)
Esempio n. 10
0
def populateDataManually():
    """Populates the database tables with dummy data.
    """
    # Populate starter data in the database
    # Bind the engine to the metadata of the Base class (enables declaratives to be accessed through a DBSession
    # instance)
    Base.metadata.bind = engine

    DBSession = sessionmaker(bind=engine)

    # A DBSession() instance establishes all conversations with the database and represents a "staging zone"
    # for all the objects loaded into the database session object. Any change made against the objects in the
    # session won't be persisted into the database until you call session.commit(). If you're not happy about the
    # changes, you can revert all of them back to the last commit by calling session.rollback()
    session = DBSession()

    # Initial dummy data.
    user1 = User(email="*****@*****.**", password="******")
    user2 = User(email="*****@*****.**", password="******")
    user3 = User(email="*****@*****.**", password="******")
    session.add(user1)
    session.add(user2)
    session.add(user3)
    session.commit()

    artist1 = Artist(name="Purity Ring", uri="dummy", followers=1)
    session.add(artist1)
    session.commit()

    album1 = Album(name="Another Eternity",
                   uri="dummyuri",
                   release_date=date.today,
                   artist_id=artist1.id, artist=artist1)
    session.add(album1)
    session.commit()

    song_objects = [
        Song(uri="dummyuri", track_number=1, name="Heartsigh", popularity=100, duration=189000, danceability=1.0,
             explicit=False, tempo=1.0, energy=1.0, instrumentalness=1.0, time_signature=100, valence=1.0,
             album_id=album1.id, album=album1),
        Song(uri="dummyuri", track_number=2, name="Bodyache", popularity=100, duration=179000, danceability=1.0,
             explicit=False, tempo=1.0, energy=1.0, instrumentalness=1.0, time_signature=100, valence=1.0,
             album_id=album1.id, album=album1),
        Song(uri="dummyuri", track_number=3, name="Push Pull", popularity=100, duration=169000, danceability=1.0,
             explicit=False, tempo=1.0, energy=1.0, instrumentalness=1.0, time_signature=100, valence=1.0,
             album_id=album1.id, album=album1),
        Song(uri="dummyuri", track_number=4, name="Repetition", popularity=100, duration=159000, danceability=1.0,
             explicit=False, tempo=1.0, energy=1.0, instrumentalness=1.0, time_signature=100, valence=1.0,
             album_id=album1.id, album=album1),
        Song(uri="dummyuri", track_number=5, name="Stranger than Earth", popularity=100, duration=149000,
             danceability=1.0, explicit=False, tempo=1.0, energy=1.0, instrumentalness=1.0, time_signature=100,
             valence=1.0, album_id=album1.id, album=album1),
        Song(uri="dummyuri", track_number=6, name="Begin Again", popularity=100, duration=139000, danceability=1.0,
             explicit=False, tempo=1.0, energy=1.0, instrumentalness=1.0, time_signature=100, valence=1.0,
             album_id=album1.id, album=album1),
        Song(uri="dummyuri", track_number=7, name="Dust Hymn", popularity=100, duration=129000, danceability=1.0,
             explicit=False, tempo=1.0, energy=1.0, instrumentalness=1.0, time_signature=100, valence=1.0,
             album_id=album1.id, album=album1),
        Song(uri="dummyuri", track_number=8, name="Flood on the Floor", popularity=100, duration=119000,
             danceability=1.0, explicit=False, tempo=1.0, energy=1.0, instrumentalness=1.0, time_signature=100,
             valence=1.0, album_id=album1.id, album=album1),
        Song(uri="dummyuri", track_number=9, name="Sea Castle", popularity=100, duration=144000, danceability=1.0,
             explicit=False, tempo=1.0, energy=1.0, instrumentalness=1.0, time_signature=100, valence=1.0,
             album_id=album1.id, album=album1),
        Song(uri="dummyuri", track_number=10, name="Stillness in Woe", popularity=100, duration=155000,
             danceability=1.0, explicit=False, tempo=1.0, energy=1.0, instrumentalness=1.0, time_signature=100,
             valence=1.0, album_id=album1.id, album=album1)
    ]
    session.add_all(song_objects)
    session.commit()