def recommended_track(spotify): form = SongSearchForm() if form.validate_on_submit(): track_ids = [form.song1_id.data, form.song2_id.data] audio_features = AudioFeatures(spotify.audio_features(tracks=track_ids)) recommendations = spotify.recommendations( limit=1, seed_tracks=track_ids, target_danceability=audio_features.mean('danceability'), target_acousticness=audio_features.mean('acousticness'), target_energy=audio_features.mean('energy'), target_instrumentalness=audio_features.mean('instrumentalness'), target_key=round(audio_features.mean('key')), target_liveness=audio_features.mean('liveness'), target_loudness=audio_features.mean('loudness'), # target_mode=audio_features.mean('mode'), # target_popularity=round(audio_features.mean('popularity')), target_speechiness=audio_features.mean('speechiness'), target_tempo=audio_features.mean('tempo'), target_time_signature=round(audio_features.mean('time_signature')), target_valence=audio_features.mean('valence') ) track = Track(recommendations['tracks'][0]) user_id = spotify.current_user()['id'] spotify.user_playlist_add_tracks(user_id, form.playlist_id.data, [track.id()], form.position.data) return redirect(url_for('playlist', playlist_id=form.playlist_id.data)) else: return redirect(request.referrer or url_for('index'))
def add_playlist(m3u: M3UList): # Create Playlist obj from M3UList obj, and Insert Playlist into DB if it does not already exist pl = Playlist.make_playlist_obj(m3u) if not Playlist.db_pl_exists(pl): try: Playlist.add_playlist(pl) except Exception as inst: print(str(inst)) else: print('Playlist {} already exists in DB'.format(pl.playlist_name)) # Insert tracks from m3u into DB if they do not already exist addable_tracks = [] for mt in m3u.tracks: dt = Track.make_Track_obj(mt) if not Track.db_trk_exists(dt): try: Track.add_track(t=dt, com=False) addable_tracks.append(dt) except Exception: raise Exception('add {} track fails'.format( dt.artist_title)) else: print('Track {} already exists in DB'.format(dt.artist_title)) addable_tracks.append(dt) db.session.commit() # add tracks to db playlist npl = Playlist.query.filter_by(playlist_name=pl.playlist_name).first() for dt in addable_tracks: npl.add_track(dt, com=False) db.session.commit()
def test_artist_track_relationship(self, memory_db): artist_1 = Artist(spotify_id='artist_spotify_id_1', artist_name='artist_name_1', followers=11) artist_2 = Artist(spotify_id='artist_spotify_id_2', artist_name='artist_name_2', followers=22) memory_db.session.add_all([artist_1, artist_2]) memory_db.session.commit() track_1 = Track(track_id='spotify_id_1', track_name='track_1', artist_id=1) track_2 = Track(track_id='spotify_id_2', track_name='track_2', artist_id=1) track_3 = Track(track_id='spotify_id_3', track_name='track_3', artist_id=2) memory_db.session.add_all([track_1, track_2, track_3]) memory_db.session.commit() assert track_1.artist == artist_1 assert track_2.artist == artist_1 assert track_3.artist == artist_2
def track_cache(id): if id == 'all': Track.cache_all() else: track = Track.query.get(id) if track is not None: track.cache() return redirect(request.referrer or url_for('index'))
def test_delete_track_automatically_removes_thumbnail_file(app, example_users): track = Track(id=1, thumbnail=str(uuid4())) db.session.add(track) db.session.commit() create_empty_file(track.thumbnail_path()) assert os.path.isfile(track.thumbnail_path()) db.session.delete(track) db.session.commit() assert not os.path.isfile(track.thumbnail_path())
def example_tracks(): t1 = Track( id=1, user_id=1, gpxfile_id=1, title="Track 01", time_start=datetime.utcnow(), time_end=datetime.utcnow() + timedelta(minutes=5), length2d=1000, length3d=1000, max_speed=20, avg_speed=10, total_uphill=50, total_downhill=50, moving_time=300, stopped_time=0, activity_mode=ActivityMode.BIKE.value, thumbnail=str(uuid4()), ) t2 = Track( id=2, user_id=1, gpxfile_id=1, title="Track 02", time_start=datetime.utcnow(), time_end=datetime.utcnow() + timedelta(minutes=5), length2d=1000, length3d=1000, max_speed=20, avg_speed=10, total_uphill=50, total_downhill=50, moving_time=300, stopped_time=0, activity_mode=ActivityMode.BIKE.value, thumbnail=str(uuid4()), ) t3 = Track( id=3, user_id=1, gpxfile_id=2, title="Track 03", time_start=datetime.utcnow(), time_end=datetime.utcnow() + timedelta(minutes=5), length2d=1000, length3d=1000, max_speed=20, avg_speed=10, total_uphill=50, total_downhill=50, moving_time=300, stopped_time=0, activity_mode=ActivityMode.HIKING.value, thumbnail=str(uuid4()), ) db.session.add_all([t1, t2, t3]) db.session.commit()
def test_db_add(): from app import db from app.models import Track fn = os.getcwd() + '\\pls\\clean\\al kooper.m3u' m3u = M3UList.m3u_clean_factory(fn, name='Al Kooper') mtrks = m3u.tracks print('mum mtracks: ', len(mtrks)) Track.add_tracks(mtrks) print('printing db Track table') tz = Track.query.all() print('num db tracks: ', len(tz)) for t in tz: print(t.artist_title)
def uploadTrack(artistId, projectId): ''' Adds new track to a project [X] ''' user = current_user if not user.superUser: return {"Errors": "User Not Authorized to create a track"} form = TrackForm() project = Project.query.get(projectId).to_dict() form['csrf_token'].data = request.cookies['csrf_token'] if form.validate_on_submit(): data = Track(name=form.data['name'], projectId=project['id']) db.session.add(data) db.session.commit() return data.to_dict()
def matching_track(phrase): # phrase may not be in the db at all, or it may be a Track-less Phrase p = Phrase.query.filter_by(name=phrase).first() if not p: p = Phrase(name=phrase) db.session.add(p) db.session.commit() form_str = "\'" + phrase + "\'" chunk_max = 10 for chunk in range(chunk_max): results = sp.search(q=form_str, type='track', limit=50, offset=chunk * 50) results = results['tracks']['items'] for track in results: if phrase == track['name'].lower(): t = Track(name=track['name'], artists=track['artists'][0]['name'], album=track['album']['name'], spot_id=track['id'], image_url=track['album']['images'][0]['url'], phrase=p) db.session.add(t) db.session.commit() return t
def import_track(gpxfile, gpx_track, gpxfile_track_id): start_time, end_time = gpx_track.get_time_bounds() moving_data = gpx_track.get_moving_data() uphill, downhill = gpx_track.get_uphill_downhill() avg_speed = (speed_to_kph(moving_data.moving_distance / moving_data.moving_time) if moving_data.moving_time > 0.0 else 0.0) track = Track( owner=gpxfile.owner, file=gpxfile, gpxfile_track_id=gpxfile_track_id, title=gpx_track.name if gpx_track.name else gpxfile.filename, time_start=start_time, time_end=end_time, length2d=gpx_track.length_2d(), length3d=gpx_track.length_3d(), max_speed=speed_to_kph(moving_data.max_speed), avg_speed=avg_speed, moving_time=moving_data.moving_time, stopped_time=moving_data.stopped_time, total_uphill=uphill, total_downhill=downhill, activity_mode=default_activity_mode_from_average_speed(avg_speed), thumbnail=str(uuid4()), ) db.session.add(track) return track
def scroll(self, cursor, size): query = Track.all() query.with_cursor(start_cursor=cursor) tracks = query.fetch(limit=size) next_cursor = query.cursor() return tracks, next_cursor
def add_update_db(url): track_id = url[-22:] track_uri = str("spotify:track:") + track_id search = sp.track(track_uri) track_name = search['name'] track_popularity = search['popularity'] duration = search['duration_ms'] explicit = search['explicit'] release_date = search['album']['release_date'] year = release_date[:3] artist_idx = search['artists'][0]['id'] search = sp.artist(artist_idx) genres = json.dumps(search['genres']) artist_name = search['name'] artist_uri = search['uri'] artist_popularity = search['popularity'] search = sp.audio_features(track_id) danceability = search[0]['danceability'] energy = search[0]['energy'] key = search[0]['key'] loudness = search[0]['loudness'] mode = search[0]['mode'] speechiness = search[0]['speechiness'] acousticness = search[0]['acousticness'] instrumentalness = search[0]['instrumentalness'] liveness = search[0]['liveness'] valence = search[0]['valence'] tempo = search[0]['tempo'] x = Artist(id=artist_idx, name=artist_name, uri=artist_uri, genres=genres, popularity=artist_popularity) y = Track(id=track_id, name=track_name, uri=track_uri, popularity=track_popularity, duration=duration, explicit=explicit, release_date=release_date, year=year, artist_id=artist_idx, danceability=danceability, energy=energy, key=key, loudness=loudness, mode=mode, speechiness=speechiness, acousticness=acousticness, instrumentalness=instrumentalness, liveness=liveness, valence=valence, tempo=tempo) sess.merge(x) sess.merge(y) sess.commit()
def add_track_to_pls(trk: Track, pl: Playlist): if Track.db_trk_exists(trk): try: pl.tracks.append(trk) db.session.commit() except Exception: print(' Failed to add {} track to {} playlist'.format( trk.artist_title, pl.playlist_name))
def transform(self, json): return Track(author=json.get(self.AUTHOR, [''])[0], lyric=json.get(self.LYRIC, [''])[0], number=int(json[self.NUMBER][0]), ref=json.get(self.REF, [None])[0], title=json[self.TITLE][0], vol=int(json.get(self.VOL, [0])[0]) if json.get( self.VOL, [0])[0] is not None else 0)
def library(): sort_by = request.args.get('sort_by', default='date_added', type=str) if sort_by == 'title': tracks = Track.query.order_by(Track.title.asc()) else: tracks = Track.query.order_by(Track.date_added.desc()) playlists = Playlist.query.order_by(Playlist.title.asc()) return render_template('library.html', tracks=tracks, are_cached=Track.are_cached(), playlists=playlists)
def add_tracks_from_dir(param): count_added = 0 count_tot = 0 exts = ['.mp3', '.m4a', '.flac', '.m4v', '.wmv'] for root, dirs, files in os.walk(Config.MEDIA_SRC_DIRS[param], topdown=True): for name in files: nname = PurePath(os.path.join(root, name)) suf = nname.suffix if suf in exts: print('loading file as Track into db: {}'.format( os.path.join(root, name))) mt = MTrack.mtrack_factory(os.path.join(root, name)) if not mt: print('MTrack {} is None'.format(str(nname))) continue t = Track.make_Track_obj(mt) if not t: print('Track {} is None'.format(str(nname))) continue try: if not Track.db_trk_exists(t): Track.add_track(t, com=True) count_added += 1 count_tot += 1 else: count_tot += 1 except Exception as inst: print(inst) print( 'rolling back and commit after failing db add {}'. format(inst)) db.session.rollback() db.session.commit() raise inst return count_tot, count_added
def post(self): data = request.get_json(force=True) if not data: return {'message': 'No input data provided'}, 400 track = Track(user_id=g.user.id, number=data['number'], title=data['title']) db.session.add(track) db.session.commit() return {'data': as_json(track)}, 200
def add_tracks_to_pls(trks: [], pl: Playlist): for t in trks: if Track.db_trk_exists(t): try: pl.tracks.append(t) except Exception: print(' Failed to add {} track to {} playlist'.format( t.artist_title, pl.playlist_name)) try: db.session.commit() except Exception: print('submit fails for added tracks to {} playlist'.format( pl.playlist_name))
def add_track(args): """Seeds an existing database with additional songs. Args: args: Argparse args - should include args.title, args.artist, args.album Returns:None """ track = Track(artist=args.artist, album=args.album, title=args.title) db.session.add(track) db.session.commit() logger.info("%s by %s from album, %s, added to database", args.title, args.artist, args.album)
def create_db(args): """Creates a database with the data model given by obj:`apps.models.Track` Args: args: Argparse args - should include args.title, args.artist, args.album Returns: None """ db.create_all() track = Track(artist=args.artist, album=args.album, title=args.title) db.session.add(track) db.session.commit() logger.info("Database created with song added: %s by %s from album, %s ", args.title, args.artist, args.album)
def tracks(album_id=None): form = CreateTrackForm() # Get MediaType information and populate the form form.media_type.choices = [ (str(media_type.media_type_id), media_type.name) for media_type in MediaType.query.order_by(MediaType.media_type_id) ] # Get Genre information and populate the form form.genre.choices = [(str(genre.genre_id), genre.name) for genre in Genre.query.order_by(Genre.genre_id)] # Get the album album = (db.session.query(Album).filter( Album.album_id == album_id).one_or_none()) form.album.data = album.title artist = album.artist form.artist.data = artist.name # Is the form valid? if form.validate_on_submit(): # Create new Track track = Track( name=form.name.data, media_type_id=form.media_type.data, genre_id=form.genre.data, composer=form.composer.data, milliseconds=form.milliseconds.data, bytes=form.bytes.data, unit_price=form.unit_price.data, ) album.tracks.append(track) db.session.add(album) db.session.commit() # Get the tracks tracks = db.session.query(Track).filter(Track.album_id == album_id).all() return render_template("tracks.html", artist=artist, album=album, tracks=tracks, form=form)
def add_entry(): """View that process a POST with new song input :return: redirect to index page """ try: track1 = Track(artist=request.form['artist'], album=request.form['album'], title=request.form['title']) db.session.add(track1) db.session.commit() logger.info("New song added: %s by %s", request.form['title'], request.form['artist']) return redirect(url_for('index')) except: logger.warning("Not able to display tracks, error page returned") return render_template('error.html')
def seed_workouts(): base_dir = os.path.dirname(__file__) # Read GPX files from the 'gpx_files' directory run_1: TextIO = open(os.path.join(base_dir, 'gpx_files', 'run_1.gpx')) run_2: TextIO = open(os.path.join(base_dir, 'gpx_files', 'boulder.gpx')) # Find a user demo_user = User.query.filter_by(username='******').first() # Create workout objects workout_1 = Workout.create_workout_from_gpx( run_1, "First Run", demo_user.id) track_1 = Track.create_track_from_gpx_track( run_2, "Boulder Skyline", demo_user.id) # Commit the session db.session.add(workout_1) db.session.add(track_1) db.session.commit()
def upload(): form = UploadForm() if form.validate_on_submit(): f = form.upload.data if not allowed_audio_file(f.filename): flash("Invalid file type.") return redirect(url_for('upload')) filename = secure_filename(f.filename) f.save(os.path.join(app.config['UPLOAD_FOLDER'], 'audio', filename)) track = Track(title=form.title.data, description=form.description.data, filename=filename, artist=current_user) db.session.add(track) db.session.commit() flash("Upload Successful.") return redirect(url_for('music', username=current_user.username)) return render_template('upload.html', title='Upload Music', form=form)
def create_new_track(path): # Get ID3 metadata on mp3 file full_path = os.path.join(SD_FOLDER, path) id3_tags = get_tags(full_path) title = id3_tags.get("title") # Retrieve title from ID3 artist_name = id3_tags.get("artist") # Retrieve artist from ID3 album_name = id3_tags.get("album") # Retrieve album from ID3 id3_genre = id3_tags.get("genre") # Retrieve genre from ID3 id3_release_date = id3_tags.get("date") # Retrieve release date from ID3 id3_cover = id3_tags.get("cover") # Retrieve cover art image data from ID3 # Construct track object track = Track.get_or_create(path=path) track.title = title # Set Artist and Album objects if artist_name is not None: artist = Artist.get_or_create(name=artist_name) track.artist = artist if album_name is not None: album = Album.get_or_create(name=album_name, artist_name=artist_name) track.album = album # Populate other ID3 columns track.genre = id3_genre track.release_date = id3_release_date # If ID3 contained cover art, create image file if id3_cover is not None: image_path = path.replace("/", " > ") + ".jpg" image_full_path = os.path.join(IMAGE_FOLDER, image_path) with open(image_full_path, 'wb') as f: f.write(id3_cover.data) track.image_path = image_path return track
def load_records(self): """ Load Artist records into Database. """ triage = [] assert len(spotify.artist_data) == len(spotify.track_data) for artist, tracks in zip(spotify.artist_data, spotify.track_data): try: artist_exists = (db.session.query(Artist.id).filter_by( spotify_id=artist['spotify_id']).scalar() is not None) # pdb.set_trace() if not artist_exists: artist_rec = Artist(**artist) db.session.add(artist_rec) for track in tracks: track_exists = (db.session.query(Track.id).filter_by( track_id=track['track_id']).scalar() is not None) if not track_exists: track_rec = Track(**track, artist=artist_rec) db.session.add(track_rec) except Exception as e: # log exception # add to triage table # Fails with UnboundLocalError triage.append({'artist': artist, 'track': track, 'Error': e}) raise db.session.commit() # pdb.set_trace() return triage
def upload_track(artist_name): artist = Artist.objects(name=artist_name).first_or_404() if current_user not in artist.members: flash('You are not authorized to upload tracks for {}'.format( artist.name)) return redirect(url_for('main.artist', artist_name=artist.name)) form = UploadTrackForm() form.genre.choices = [(genre.id, genre.name) for genre in Genre.objects.order_by('name')] if form.validate_on_submit(): file = form.track.data if not allowed_file(file.filename): flash('Only music files are allowed') return render_template('upload_track.html', form=form, artist=artist, title='Upload Track') file.filename = secure_filename(file.filename) s3_filepath, cloudfront_filepath = upload_file_to_s3( file, current_app.config['S3_BUCKET']) track_exists = Track.objects(s3_filepath=s3_filepath, cloudfront_filepath=cloudfront_filepath ).first() is not None # 1 if track exists if s3_filepath is not None and cloudfront_filepath is not None and not track_exists: new_track = Track(track_name=form.track_name.data, artist=artist, duration=0, genre=[ Genre.objects(id=genre).first() for genre in form.genre.data ], s3_filepath=s3_filepath, cloudfront_filepath=cloudfront_filepath) new_track.save(cascade=True) # Saves the track in the mongoDB # filepath = os.path.join(current_app.config['UPLOAD_FOLDER'], file.filename) # new_track = Track(track_name=form.track_name.data, artist=artist, duration=0, # genre=[Genre.objects(id=genre).first() for genre in form.genre.data], filepath=filepath) # new_track.save(cascade=True) # Saves the track in the mongoDB # file.save(filepath) artist.tracks.append(new_track) artist.save(cascade=True) # Save artist with new track flash('Track successfully uploaded') return redirect(url_for('main.artist', artist_name=artist_name)) else: if track_exists: flash('Track already exists!') return render_template('upload_track.html', form=form, artist=artist, title='Upload Track') else: flash('Error uploading file') return render_template('upload_track.html', form=form, artist=artist, title='Upload Track') return render_template('upload_track.html', form=form, artist=artist, title='Upload Track')
def get_track(track_name): track = Track.objects(track_name=track_name).first_or_404() track_url = track.filepath return jsonify({'track_url': track_url})
def test_can_delete_track_thumbnail(app): track = Track(thumbnail=str(uuid4())) create_empty_file(track.thumbnail_path()) assert os.path.isfile(track.thumbnail_path()) track.delete_thumbnail_file() assert not os.path.isfile(track.thumbnail_path())
def test_track_thumbnail_path_returns_correct_filename(app): app.config["THUMBNAILS_FOLDER"] = "thumbnails" uuid = str(uuid4()) track = Track(thumbnail=uuid) assert track.thumbnail_path() == os.path.join("thumbnails", f"{uuid}.png")