def test_get_many(server, artist, arguments, names): with server.app_context(): db.session.add(Album('ab-1AB-12-12345', 'a', artist)) db.session.add(Album('ab-1AB-12-12346', 'b', artist)) db.session.add(Album('ab-1AB-12-12347', 'c', artist)) db.session.commit() r = requests.get(server.url + "/albums?{}".format(urlencode(arguments))) assert r.status_code == 200 items = r.json() assert len(items) == len(names) assert list(map(lambda x: x["name"], items)) == names
def post(self): self.resource_fields['data'] = fields.Nested(self.album_fields) args = self.parser.parse_args() name = args.get('name', '') artist = args.get('artist', '') is_hot = args.get('is_hot', 0) classification = args.get('classification', []) cl_obj_list = Classification.select().where( Classification.id << classification) album = Album(name=name, artist=artist, is_hot=is_hot) album.save() cl_json_list = [] if cl_obj_list.exists(): for item in cl_obj_list: album.classification.add(item) cl_json_list.append(model_to_dict(item)) album.save() album = model_to_dict(album) album['classification'] = cl_json_list resp = {'error_code': 0, 'data': album} return make_response(json.dumps(marshal(resp, self.resource_fields)), 200)
def _cache_albums_async(app, refresh_thumbnails=False, refresh_dates=False): with app.app_context(): album_manager = GPhotosAlbum(service) current_ids = list() for a in album_manager.list(): album = Album.query.filter_by(gphotos_id=a.get("id")).first() if not album: album = Album() album.gphotos_id = a.get("id") if not album.end_date or refresh_dates: start_date, end_date = _get_album_date_range(album.gphotos_id) album.start_date = start_date album.end_date = end_date current_ids.append(a.get("id")) album.title = a.get("title") album.url_title = normalize_for_url(a.get("title")) album.items_count = a.get("mediaItemsCount") db.session.add(album) thumbnail = os.path.join(app.config["ALBUM_THUMB_PATH"], a.get("id") + ".jpg") if not os.path.exists(thumbnail) or refresh_thumbnails: urllib.request.urlretrieve( a.get("coverPhotoBaseUrl") + "=w300-h200-c", os.path.join(app.config["ALBUM_THUMB_PATH"], a.get("id") + ".jpg"), ) db.session.commit() # delete from db albums no longer in google photos stmt = delete(Album).where( Album.gphotos_id.notin_(current_ids)).execution_options( synchronize_session="fetch") db.session.execute(stmt) db.session.commit()
def admin_album(): if request.method == 'POST': album_name = request.form.get('album_name') album_state = request.form.get('album_state') or '1' album_desc = request.form.get('album_desc') if not album_name: return make_response(jsonify({"code": 1, "message": "请填写相册名称!"})) try: db.session.add(Album(album_name=album_name, album_desc=album_desc)) db.session.commit() except Exception: db.rollback() return make_response( jsonify({ "code": 1, "message": "新增失败,请联系管理员!" })) finally: db.session.close() return make_response(jsonify({"code": 0, "message": "新建成功!"})) albums = db.session.query( Album.album_id, Album.album_name, Album.album_slt).filter(Album.album_status == '1').all() return render_template('album/index.html', albums=albums)
def albums(artist_id=None): form = CreateAlbumForm() # did we get an artist id? if artist_id is not None: # Get the artist artist = (db.session.query(Artist).filter( Artist.artist_id == artist_id).one_or_none()) form.artist.data = artist.name # otherwise, no artist else: artist = None # Is the form valid? if form.validate_on_submit(): # Create new Album album = Album(title=form.title.data) artist.albums.append(album) db.session.add(artist) db.session.commit() return redirect(url_for("albums_bp.albums", artist_id=artist_id)) # Start the query for albums query = db.session.query(Album) # Display the albums for the artist passed? if artist_id is not None: query = query.filter(Album.artist_id == artist_id) albums = query.order_by(Album.title).all() return render_template("albums.html", artist=artist, albums=albums, form=form)
def _make_db_album(sp_album): db_album = Album(id=sp_album['id'], name=sp_album['name'], total_tracks=sp_album['total_tracks']) db.session.add(db_album) _add_item_artists(db_album, sp_album['artists']) _add_item_tracks(db_album, sp_album['tracks']) return db_album
def test_get_one(server, artist): with server.app_context(): album = Album('ab-1AB-12-12345', 'a', artist) db.session.add(album) db.session.commit() assert Album.query.count() == 1 r = requests.get(server.url + "/album/{}".format(artist.id)) assert r.status_code == 200 assert r.json()['name'] == artist.name
def setUp(self): super(EntryResourceTest, self).setUp() self.album1 = Album(title='test_title_1', order_num=1) self.album1.save() self.album2 = Album(title='test_title_2', order_num=1) self.album2.save() self.foto1 = Foto(album=self.album1, title='foto1', image='test_image_1.jpg') self.foto2 = Foto(album=self.album1, title='foto2', image='test_image_2.jpg') self.video1 = Video(album=self.album2, title='video1', video_link='test_video_link2') self.video2 = Video(album=self.album2, title='video2', video_link='test_video_link2')
def add_tl_to_fav(id): """ Add an album from tolisten to favorites """ toadd = ToListen.query.get(id) form = AlbumForm(request.form) # the suggested rank should be the next available rank # e.g. if there are 200 albums currently in the favorites list, # the suggested rank should be 201 rank = db.session.query(func.max(Album.rank).label("rank")).scalar() + 1 if request.method == 'POST' and form.validate_on_submit(): album = Album() album.rank = form.rank.data album.title = form.title.data album.artist = form.artist.data album.year = form.year.data album.last_played = datetime.strptime(form.last_played.data, '%Y-%m-%d') album.user_id = current_user.id # make sure the added album's ranking is no lower than what makes sense # e.g. if there are currently 200 albums in favorites, # the lowest that makes sense is 201 if int(album.rank) > rank: album.rank = rank elif int(album.rank) < rank: # get every album lower *numerically higher) in current ranking # than the ranking we are trying to add to # and increment ranking by 1 # e.g. there are 200 albums and we assign a ranking of 195 to new album # album currently ranked 195 will become 196, # album currently ranked 196 will becomes 197... # ...album current ranked 200 will become 201 to_move = (Album.query.filter_by(user_id=current_user.id).filter( Album.rank >= int(form.rank.data)).filter( Album.rank < rank).order_by(Album.rank.desc()).all()) for a in to_move: a.rank += 1 db.session.commit() db.session.add(album) title, artist = toadd.title, toadd.artist ToListen.query.filter(ToListen.id == id).delete() db.session.commit() flash(f'Successfully added album {album.title} by {album.artist}') flash(f'Deleted {title} by {artist} from albums to listen') return redirect(url_for('favorites')) # addt'l variables curr_dt = datetime.now().strftime('%Y-%m-%d') curr_dt = datetime.now().strftime('%Y-%m-%d') return render_template('addalbum.html', form=form, last_played=curr_dt, rank=rank, toadd=toadd)
def setSongAlbum(song, album_name): app.logger.info('setSongAlbum') if not album_name: raise Exception('Song has no album name given') # update tag app.logger.info('Updating album {} for song {}'.format(album_name, song)) if song.path_name.lower().endswith('mp3'): tags = ID3(song.abs_path) tags["TALB"] = TALB(encoding=3, text=u'{}'.format(album_name)) tags.save(song.abs_path) elif song.path_name.lower().endswith('m4a'): tags = MP4(song.abs_path) raise Exception('Do song info for mp4') # get track info try: trck = tags['TRCK'].text[0] except KeyError: trck = '' if '/' in trck: track_number, total_tracks = trck.split('/') else: track_number = trck total_tracks = None try: total_tracks = int(total_tracks) except (ValueError, TypeError): total_tracks = None disc_number = int( tags['TPOS'].text[0].split('/')[0]) if 'TPOS' in tags else 1 total_discs = int(tags['TPOS'].text[0].split( '/')[1]) if 'TPOS' in tags and '/' in tags['TPOS'].text[0] else 1 year = int(tags['TDRC'].text[0].year) if 'TDRC' in tags else None # update model album = Album.query.filter_by(name=album_name, artist=song.artist).first() if not album: album = Album(album_name, song.artist) album.disc_number = disc_number album.total_discs = total_discs album.total_tracks = total_tracks album.year = year db.session.add(album) db.session.commit() app.logger.info('Created new album {} <= {}'.format(album, album_name)) song.album_id = album.id album.count_songs = len(album.songs) db.session.commit() app.logger.info('Update song in db')
def test_delete(server, artist): with server.app_context(): album = Album('ab-1AB-12-12345', 'a', artist) db.session.add(album) db.session.commit() assert Album.query.count() == 1 r = requests.delete(server.url + "/album/{}".format(artist.id)) assert r.status_code == 204 with server.app_context(): assert Album.query.count() == 0
def create_album(): form = AlbumForm() if form.validate_on_submit(): new_album = Album(name_album=form.name.data, publish_date=form.publish_date.data, songs=form.songs.data) db.session.add(new_album) db.session.commit() flash('New author created successfully.') return redirect(url_for('main.album_detail', album_id=new_album.id)) # if form was not valid, or was not submitted yet return render_template('create_album.html', form=form)
def test_put_errors(server, artist, data, field): with server.app_context(): db.session.add(artist) album = Album('ab-1AB-12-12345', 'a', artist) db.session.add(album) db.session.commit() album_id = album.id with server.app_context(): assert Album.query.count() == 1 r = requests.put(server.url + "/album/{}".format(album_id), data=data) assert r.status_code == 422 assert field in r.json()['message'] assert Album.query.count() == 1
def new_album(parent_id=None): ''' New album ''' form = NewAlbumForm() if parent_id: parent = Album.query.get_or_404(parent_id) else: parent = None if form.validate_on_submit(): album = Album(title=form.title.data, description=form.description.data, author=current_user, parent=parent) db.session.add(album) db.session.commit() flash(gettext('New album \'%(album)s\' added', album=album.title)) return redirect(url_for('.index')) return render_template('new_album.html', form=form)
def add_favorite(): """ Add an album to favorites """ form = AlbumForm(request.form) rankrow = (Album.query.filter_by(user_id=current_user.id).order_by( Album.rank.desc()).limit(1).all()) rank = rankrow[0].rank + 1 if request.method == 'POST' and form.validate_on_submit(): album = Album() album.rank = form.rank.data album.title = form.title.data album.artist = form.artist.data album.year = form.year.data album.last_played = datetime.strptime(form.last_played.data, '%Y-%m-%d') album.user_id = current_user.id # make sure the added album's ranking is no lower than what makes sense # e.g. if there are currently 200 albums in favorites, # the lowest that makes sense is 201 if int(album.rank) > rank: album.rank = rank elif int(album.rank) < rank: # get every album lower *numerically higher) in current ranking # than the ranking we are trying to add to # and increment ranking by 1 # e.g. there are 200 albums and we assign a ranking of 195 to new album # album currently ranked 195 will become 196, # album currently ranked 196 will becomes 197... # ...album current ranked 200 will become 201 to_move = (Album.query.filter_by(user_id=current_user.id).filter( Album.rank >= int(form.rank.data)).filter( Album.rank < rank).order_by(Album.rank.desc()).all()) for a in to_move: a.rank += 1 db.session.commit() db.session.add(album) db.session.commit() flash(f'Successfully added album {album.title} by {album.artist}') return redirect(url_for('favorites')) # addt'l variables curr_dt = datetime.now().strftime('%Y-%m-%d') return render_template('addalbum.html', form=form, last_played=curr_dt, rank=rank, toadd=None)
def api_albums_index(): if request.method == 'POST': artist_name = request.form['album[artist_name]'] name = request.form['album[name]'] order = 0 new_album = Album(artist_name=artist_name, name=name, order=order) db.session.add(new_album) db.session.commit() albums = Album.query.all() album_dicts = [] for album in albums: dict = album.__dict__ dict['category'] = ['Modern', 'Classical'][album.category - 1] del dict['_sa_instance_state'] album_dicts.append(dict) result = {} result['albums'] = to_camel_case(album_dicts) return result
def populate_database(session): artist = Artist() artist.name = "Test Artist" artist.spotify_uri = "spotify:artist:arn" session.add(artist) album = Album() album.name = "Test Album" album.artists.append(artist) album.spotify_uri = "spotify:album:arn" session.add(album) media = Media() media.tmdb_id = "TMDB_ID" media.name = "Test media" media.type = 1 session.add(media) session.commit()
def test_put_same_isrc(server, artist): with server.app_context(): db.session.add(artist) album = Album('ab-1AB-12-12345', 'a', artist) db.session.add(album) db.session.commit() album_id = album.id assert Album.query.count() == 1 data = {"isrc": 'ab-1AB-12-12345'} r = requests.put(server.url + "/album/{}".format(album_id), data=data) assert r.status_code == 200 assert r.json()['isrc'] == data['isrc'] with server.app_context(): assert Album.query.count() == 1 album = Album.query.get(album_id) assert album.isrc == data['isrc']
def album(artist_id): form = AlbumForm() album = Album.query.filter_by(artist_id=artist_id).all() artist = Artist.query.filter_by(id=artist_id).first() song = db.session.query(Album, Song).join( Song, Album.id == Song.album_id).filter(Album.artist_id == artist_id) youtube = Album.query.filter_by(artist_id=artist_id).first() if form.validate_on_submit(): newalbum = Album(albumname=form.albumname.data, albumlogo=form.albumlogo.data, albumlink=form.albumlink.data, artist_id=artist_id) db.session.add(newalbum) db.session.commit() return redirect(url_for('music')) return render_template('artist.html', title='Artist', album=album, artist=artist, youtube=youtube, form=form, song=song)
def test_put(server, artist): with server.app_context(): db.session.add(artist) artist2 = Artist("b") db.session.add(artist2) db.session.commit() album = Album('ab-1AB-12-12345', 'a', artist) db.session.add(album) db.session.commit() artist_id2 = artist2.id album_id = album.id assert Album.query.count() == 1 data = { "isrc": 'ab-1AB-12-12346', "artist_id": artist_id2, "name": "b", "label": "label2", "year": 2011, } r = requests.put(server.url + "/album/{}".format(album_id), data=data) assert r.status_code == 200 response_data = r.json() assert response_data['isrc'] == data['isrc'] assert response_data['artist']['id'] == data['artist_id'] assert response_data['name'] == data['name'] assert response_data['label'] == data['label'] assert response_data['year'] == data['year'] with server.app_context(): assert Album.query.count() == 1 album = Album.query.first() assert album.isrc == data['isrc'] assert album.artist_id == data['artist_id'] assert album.name == data['name'] assert album.label == data['label'] assert album.year == data['year']
def test_post_errors_on_unique_isrc(server, artist): with server.app_context(): db.session.add(artist) db.session.commit() artist_id = artist.id with server.app_context(): album = Album('ab-1AB-12-12345', 'a', artist) db.session.add(album) db.session.commit() assert Album.query.count() == 1 r = requests.post(server.url + "/albums", data={ "isrc": 'ab-1AB-12-12345', "name": "b", "artist_id": artist_id, }) assert r.status_code == 422 assert 'isrc' in r.json()['message'] assert Artist.query.count() == 1
def post(self): data = parser.parse_args() required = ["name", "url", "year", "artist"] if any(val is None for key, val in data.items() if key in required): api.abort(400, "Value of a required key is missing", required=required) #return {"error": "name, url, year and artist are required"}, 400 data = clean_data(data) try: album = Album(**data) db.session.add(album) db.session.commit() except: api.abort(409, "Album already exists") #return {"error": f"Album {data['name']} already exists"}, 409 return api.marshal(album, serializer, skip_none=True, mask="id,name,artist,year,url,genre"), 201
def albumsAdd(): form = AlbumForm() # 提交 print(form.validate_on_submit()) print(form.errors) if form.validate_on_submit(): data = form.data print(data) # 图片处理 images = request.values.get('images', '') imagesdata = images.split(';') imagesnew = '' print(images) print(imagesdata) album = Album(title=data["title"], picture=data["picture"].replace('/temp/', '/images/'), like_num=int(data["like_num"]), sort=int(data["sort"]), pictures=[]) # if images: for index in range(len(imagesdata)): print(index) print(imagesdata[index]) if imagesdata[index]: move_file(imagesdata[index]) imagesnew = imagesdata[index].replace('/temp/', '/images/') album.pictures.append(Picture(path=imagesnew, sort=int(index))) db.session.add(album) db.session.commit() flash("success!", "ok") return redirect(url_for('admin.albums')) return render_template('admin/album/create.html', form=form)
path = sys.argv[1] if len(sys.argv) > 1 else 'sample.csv' sample = pd.read_csv(path) if '.jpg' in sample.iloc[0].album_id: sample['album_id'] = sample['album_id'].str.strip('.jpg').astype('int') else: sample['album_id'] = sample['album_id'].astype('int') sample = sample[sample['remove'].isna()] # Create mapping of genre name to id to assign albums a proper genre id genres = Genre.query.all() genre_map = {g.name: g.genre_id for g in genres} for album in sample.itertuples(): db.session.merge(Album(album_id=album.album_id, prediction_id=genre_map.get(album.predicted_genre), confidence=album.correct_certainty)) p = {'country': 0.2727, 'electronic': 0.3750, 'folk': 0.1667, 'indie': 0.1020, 'metal': 0.4375, 'pop': 0.1702, 'rap': 0.930, 'rock': 0.1667} for g in p.keys(): genre = Genre.query.get(genre_map.get(g)) genre.model_performance = p.get(g) db.session.merge(genre)
mister_3 = User(username = '******', email = '*****@*****.**', avatar = 'https://64.media.tumblr.com/344fe0498afb2560cc8f09d5099f0bca/5e7104cb65b9b19f-39/s400x600/27aefbdd04d1d6d0a1a8ef38b716bf75d3fc3121.png', encrypted_password=bcrypt.hashpw( "password".encode('utf-8'), bcrypt.gensalt(14))) miss_monday = User(username = '******', email = '*****@*****.**', avatar = 'https://64.media.tumblr.com/a943ef66b1ba80fd211fb96b333eb011/5e7104cb65b9b19f-3c/s400x600/76b8ab1496d99e508c69f3b91adaf65077e3ea3e.png', encrypted_password=bcrypt.hashpw( "password".encode('utf-8'), bcrypt.gensalt(14))) Zackitty = User(username = '******', email = '*****@*****.**', avatar = 'https://64.media.tumblr.com/ed6c711e9bcf78d9e07ed9d49f74a49a/5e7104cb65b9b19f-77/s400x600/1fef80e0b5e89ad70a5d526fdcf0d706994c724a.jpg', encrypted_password=bcrypt.hashpw( "onepiece".encode('utf-8'), bcrypt.gensalt(14))) miss_goldenweek = User(username = '******', email = '*****@*****.**', avatar = 'https://64.media.tumblr.com/3e0c719e439014c6b222de0b6ba8098c/5e7104cb65b9b19f-41/s250x400/7e0acb01126538cec6adeb35272514439aac799f.jpg', encrypted_password=bcrypt.hashpw( "password".encode('utf-8'), bcrypt.gensalt(14))) goldenAlbum = Album(content = "Miss Goldenweek's Album", name = "Golden Album", description="Miss Goldenweek's Album", user_id=4) photo1 = Photo(content = 'https://64.media.tumblr.com/7191f61d196fdd6bedad9e437adb7324/ec8aafd081f42e60-5f/s540x810/31e56d5ad5935b0dad3342636778d8bde7705077.png', name="Rei", description="Rei sitting in class", user_id=1, album_id=1) photo2 = Photo(content = 'https://64.media.tumblr.com/9261589530856437c1a899fc04f57bd2/tumblr_o2x1sboh5i1rves7ho5_640.jpg', name="Sandwich Bot", description="Knock-off Spongebob Curtains", user_id=1, album_id=1) photo3 = Photo(content = 'https://64.media.tumblr.com/14a638b3946dcaa319ac2061fc68a618/264c604a5399eff0-1a/s1280x1920/bc65a91da17603fc3a778998240fafe12c32ec9f.jpg', name="Jerri Blank", description="Jerri contemplating", user_id=1, album_id=1) # photo4 = Photo(content = 'https://64.media.tumblr.com/92041d8e302c03eadc903d964da5f3c6/fee9ff38989d5868-42/s500x750/7c06220e25732be3554ce490642d8af15aaa6e7d.jpg', # name="Moguta", description="Moguta doesn't like you", user_id=1, album_id=1) db.session.add(demo_user) db.session.add(mister_3) db.session.add(miss_monday)
def create_album(): form_album = CreateAlbumForm() error = False if "profile" in session: user_id = session["profile"].get("user_id") userinfo = session["profile"] logged_in = True else: user_id = "ANON" userinfo = None logged_in = False if request.method == "GET": return render_template( "create_album.html", form=form_album, success=False, logged_in=logged_in, userinfo=userinfo, ) elif form_album.validate_on_submit(): form_values = request.form album_name = hashlib.md5( "unicorn".encode("utf-8") + str(time.time()).encode("utf-8")).hexdigest()[:10] try: bucket_name, bucket_response = create_bucket( bucket_prefix=album_name, s3_connection=s3_resource) album = Album(name=form_values.get("name"), url=album_name, user_id=user_id) db.session.add(album) db.session.flush() for filename in request.files.getlist(form_album.photo.name): file_name = secure_filename(filename.filename) name = hashlib.md5( "admin".encode("utf-8") + str(time.time()).encode("utf-8")).hexdigest()[:10] file_name = f'{name}.{file_name.split(".")[-1]}' s3_resource.Bucket(bucket_name).put_object( Body=filename, Key=file_name, ContentType=request.mimetype, ACL="public-read", ) db_file_url = f"https://{bucket_name}.s3.amazonaws.com/{file_name}" image = Image(url=db_file_url, album_id=album.id) db.session.add(image) db.session.commit() success = True # if error we rollback the commit except BaseException: error = True db.session.rollback() print(sys.exc_info()) delete_all_objects(bucket_name) s3_resource.Bucket(bucket_name).delete() except boto3.exception.ParamValidationError: error = True db.session.rollback() print(sys.exc_info()) finally: db.session.close() # we flash an error if the creation of an Album didn't work if error: flash("An error occurred. Try again") success = False else: flash("The album was created. Accessible at this address : {}". format("https://one-pic-one-day.herokuapp.com/" + album_name)) else: print("error") success = False return render_template( "create_album.html", form=form_album, success=success, logged_in=logged_in, userinfo=userinfo, )
def updateDBInfo(response, track): tags = Information() # Changing tags in the database if 'TITLE' in response and response['TITLE'] != '': tags.trackTitle = strip_tags(response['TITLE']).lstrip().rstrip() track.title = tags.trackTitle if 'ARTISTS' in response and response['ARTISTS'] != '': tags.trackArtist = strip_tags( response['ARTISTS']).lstrip().rstrip().split(',') artists = [] for artist in tags.trackArtist: if Artist.objects.filter(name=artist).count() == 0: newArtist = Artist() newArtist.name = artist newArtist.save() artists.append(Artist.objects.get(name=artist)) track.artist.clear() for artist in artists: track.artist.add(artist) if 'PERFORMER' in response and response['PERFORMER'] != '': tags.trackPerformer = strip_tags( response['PERFORMER']).lstrip().rstrip() track.performer = tags.trackPerformer if 'COMPOSER' in response and response['COMPOSER'] != '': tags.trackComposer = strip_tags(response['COMPOSER']).lstrip().rstrip() track.composer = tags.trackComposer if 'YEAR' in response and response['YEAR'] != '': tags.trackYear = checkIntValueError(response['YEAR']) track.year = tags.trackYear if 'TRACK_NUMBER' in response and response['TRACK_NUMBER'] != '': tags.trackNumber = checkIntValueError(response['TRACK_NUMBER']) track.number = tags.trackNumber if 'BPM' in response and response['BPM'] != '': track.bpm = checkIntValueError(response['BPM']) if 'LYRICS' in response and response['LYRICS'] != '': tags.lyrics = strip_tags(response['LYRICS']).lstrip().rstrip() track.lyrics = tags.lyrics if 'COMMENT' in response and response['COMMENT'] != '': tags.comment = strip_tags(response['COMMENT']).lstrip().rstrip() track.comment = tags.comment if 'GENRE' in response and response['GENRE'] != '': tags.trackGenre = strip_tags(response['GENRE']).lstrip().rstrip() if Genre.objects.filter(name=tags.trackGenre).count() == 0: genre = Genre() genre.name = tags.trackGenre genre.save() genre = Genre.objects.get(name=tags.trackGenre) track.genre = genre if 'COVER' in response: md5Name = hashlib.md5() if str(response['COVER'].split(",")[0]) == "image/png": extension = "png" else: extension = "jpg" md5Name.update(base64.b64decode(str(response['COVER'].split(",")[1]))) # Check if the folder exists filePath = "/ManaZeak/static/img/covers/" if not os.path.isdir(filePath): os.mkdir(filePath) # Create the folder filePath += +md5Name.hexdigest() + extension # if the filePath is the same, then the md5 hash of the image is # the same, therefore the images are the same, therefore do nothing if not os.path.isfile(filePath): with open(filePath, 'wb+') as destination: # Split the header with MIME type tags.cover = base64.b64decode( str(response['COVER'].split(",")[1])) destination.write(tags.cover) track.coverLocation = md5Name.hexdigest() + extension if 'ALBUM_TITLE' in response and 'ALBUM_ARTISTS' in response and response['ALBUM_TITLE'] != '' \ and response['ALBUM_ARTISTS'] != '': tags.albumTitle = strip_tags(response['ALBUM_TITLE']).lstrip().rstrip() tags.albumArtist = strip_tags( response['ALBUM_ARTISTS']).lstrip().rstrip().split(',') if Album.objects.filter(title=tags.albumTitle).count() == 0: album = Album() album.title = tags.albumTitle album.save() album = Album.objects.get(title=tags.albumTitle) album.artist.clear() for artist in tags.albumArtist: if Artist.objects.filter(name=artist).count() == 0: newArtist = Artist() newArtist.name = artist newArtist.save() album.artist.add(Artist.objects.get(name=artist)) if 'ALBUM_TOTAL_DISC' in response and response[ 'ALBUM_TOTAL_DISC'] != '': tags.albumTotalDisc = checkIntValueError( response['ALBUM_TOTAL_DISC']) album.totalDisc = tags.albumTotalDisc if 'DISC_NUMBER' in response and response['DISC_NUMBER'] != '': tags.albumDiscNumber = checkIntValueError(response['DISC_NUMBER']) track.discNumber = tags.albumDiscNumber if 'ALBUM_TOTAL_TRACK' in response and response[ 'ALBUM_TOTAL_TRACK'] != '': tags.albumTotalTrack = checkIntValueError( response['ALBUM_TOTAL_TRACK']) album.totalTrack = tags.albumTotalTrack album.save() track.album = album track.save() return tags
def init(): # create artists artists = [ 'Mickey Mouse', 'Goofy', 'Bart Simpson', 'Homer', 'Bruce Lee', ] for name in artists: artist = Artist.query.filter_by(name=name).first() if artist is None: artist = Artist(name=name) db.session.add(artist) try: db.session.commit() except: db.session.rollback() # create genre genres = [ 'Rock', 'Pop', 'Hip-hop', 'Rap', 'R & R', 'Classical', 'Techno', 'Jazz', 'Folk', 'Country', ] for name in genres: genre = Genre.query.filter_by(name=name).first() if genre is None: genre = Genre(name=name) db.session.add(genre) try: db.session.commit() except: db.session.rollback() # create albums albums = [ ('Becon and Eggs', 2, 4, '/shutify/app/static/images/artwork/clearday.jpg', '/static/images/artwork/clearday.jpg'), ('Pizza head', 5, 10, '/shutify/app/static/images/artwork/energy.jpg', '/static/images/artwork/energy.jpg'), ('Summer Hits', 3, 1, '/shutify/app/static/images/artwork/goinghigher.jpg', '/static/images/artwork/goinghigher.jpg'), ('The movie soundtrack', 2, 9, '/shutify/app/static/images/artwork/funkyelement.jpg', '/static/images/artwork/funkyelement.jpg'), ('Best of the Worst', 1, 3, '/shutify/app/static/images/artwork/popdance.jpg', '/static/images/artwork/popdance.jpg'), ('Hello World', 3, 6, '/shutify/app/static/images/artwork/ukulele.jpg', '/static/images/artwork/ukulele.jpg'), ('Best beats', 4, 7, '/shutify/app/static/images/artwork/sweet.jpg', '/static/images/artwork/sweet.jpg'), ] for item in albums: album = Album.query.filter_by(title=item[0]).first() if album is None: album = Album( title=item[0], artist_id=item[1], genre_id=item[2], artwork_path=item[3], artwork_url=item[4], ) db.session.add(album) try: db.session.commit() except: db.session.rollback() # songs songs = [ ('Acoustic Breeze', 1, 5, 8, timedelta(minutes=2, seconds=37), '/shutify/app/static/music/bensound-acousticbreeze.mp3', '/static/music/bensound-acousticbreeze.mp3', 1, 10), ('A new beginning', 1, 5, 1, timedelta(minutes=2, seconds=35), '/shutify/app/static/music/bensound-anewbeginning.mp3', '/static/music/bensound-anewbeginning.mp3', 2, 4), ('Better Days', 1, 5, 2, timedelta(minutes=2, seconds=33), '/shutify/app/static/music/bensound-betterdays.mp3', '/static/music/bensound-betterdays.mp3', 3, 10), ('Buddy', 1, 5, 3, timedelta(minutes=2, seconds=2), '/shutify/app/static/music/bensound-buddy.mp3', '/static/music/bensound-buddy.mp3', 4, 13), ('Clear Day', 1, 5, 4, timedelta(minutes=1, seconds=29), '/shutify/app/static/music/bensound-clearday.mp3', '/static/music/bensound-clearday.mp3', 5, 8), ('Going Higher', 2, 1, 1, timedelta(minutes=4, seconds=4), '/shutify/app/static/music/bensound-goinghigher.mp3', '/static/music/bensound-goinghigher.mp3', 1, 34), ('Funny Song', 2, 4, 2, timedelta(minutes=3, seconds=7), '/shutify/app/static/music/bensound-funnysong.mp3', '/static/music/bensound-funnysong.mp3', 2, 12), ('Funky Element', 2, 1, 3, timedelta(minutes=3, seconds=8), '/shutify/app/static/music/bensound-funkyelement.mp3', '/static/music/bensound-funkyelement.mp3', 2, 26), ('Extreme Action', 2, 1, 4, timedelta(minutes=8, seconds=3), '/shutify/app/static/music/bensound-extremeaction.mp3', '/static/music/bensound-extremeaction.mp3', 3, 29), ('Epic', 2, 4, 5, timedelta(minutes=2, seconds=58), '/shutify/app/static/music/bensound-epic.mp3', '/static/music/bensound-epic.mp3', 3, 17), ('Energy', 2, 1, 6, timedelta(minutes=2, seconds=59), '/shutify/app/static/music/bensound-energy.mp3', '/static/music/bensound-energy.mp3', 4, 26), ('Dubstep', 2, 1, 7, timedelta(minutes=2, seconds=3), '/shutify/app/static/music/bensound-dubstep.mp3', '/static/music/bensound-dubstep.mp3', 5, 22), ('Happiness', 3, 6, 8, timedelta(minutes=4, seconds=21), '/shutify/app/static/music/bensound-happiness.mp3', '/static/music/bensound-happiness.mp3', 5, 3), ('Happy Rock', 3, 6, 9, timedelta(minutes=1, seconds=45), '/shutify/app/static/music/bensound-happyrock.mp3', '/static/music/bensound-happyrock.mp3', 4, 8), ('Jazzy Frenchy', 3, 6, 10, timedelta(minutes=1, seconds=44), '/shutify/app/static/music/bensound-jazzyfrenchy.mp3', '/static/music/bensound-jazzyfrenchy.mp3', 3, 11), ('Little Idea', 3, 6, 1, timedelta(minutes=2, seconds=49), '/shutify/app/static/music/bensound-littleidea.mp3', '/static/music/bensound-littleidea.mp3', 2, 12), ('Memories', 3, 6, 2, timedelta(minutes=3, seconds=50), '/shutify/app/static/music/bensound-memories.mp3', '/static/music/bensound-memories.mp3', 1, 6), ('Moose', 4, 7, 1, timedelta(minutes=2, seconds=43), '/shutify/app/static/music/bensound-moose.mp3', '/static/music/bensound-moose.mp3', 5, 2), ('November', 4, 7, 2, timedelta(minutes=3, seconds=32), '/shutify/app/static/music/bensound-november.mp3', '/static/music/bensound-november.mp3', 4, 5), ('Of Elias Dream', 4, 7, 3, timedelta(minutes=4, seconds=58), '/shutify/app/static/music/bensound-ofeliasdream.mp3', '/static/music/bensound-ofeliasdream.mp3', 3, 5), ('Pop Dance', 4, 7, 2, timedelta(minutes=2, seconds=42), '/shutify/app/static/music/bensound-popdance.mp3', '/static/music/bensound-popdance.mp3', 2, 11), ('Retro Soul', 4, 7, 5, timedelta(minutes=3, seconds=36), '/shutify/app/static/music/bensound-retrosoul.mp3', '/static/music/bensound-retrosoul.mp3', 1, 11), ('Sad Day', 5, 2, 1, timedelta(minutes=2, seconds=28), '/shutify/app/static/music/bensound-sadday.mp3', '/static/music/bensound-sadday.mp3', 1, 9), ('Sci-fi', 5, 2, 2, timedelta(minutes=4, seconds=44), '/shutify/app/static/music/bensound-scifi.mp3', '/static/music/bensound-scifi.mp3', 2, 9), ('Slow Motion', 5, 2, 3, timedelta(minutes=3, seconds=26), '/shutify/app/static/music/bensound-slowmotion.mp3', '/static/music/bensound-slowmotion.mp3', 3, 4), ('Sunny', 5, 2, 4, timedelta(minutes=2, seconds=20), '/shutify/app/static/music/bensound-sunny.mp3', '/static/music/bensound-sunny.mp3', 4, 19), ('Sweet', 5, 2, 5, timedelta(minutes=5, seconds=7), '/shutify/app/static/music/bensound-sweet.mp3', '/static/music/bensound-sweet.mp3', 5, 17), ('Tenderness ', 3, 3, 7, timedelta(minutes=2, seconds=3), '/shutify/app/static/music/bensound-tenderness.mp3', '/static/music/bensound-tenderness.mp3', 4, 13), ('The Lounge', 3, 3, 8, timedelta(minutes=4, seconds=16), '/shutify/app/static/music/bensound-thelounge.mp3', '/static/music/bensound-thelounge.mp3', 3, 7), ('Ukulele', 3, 3, 9, timedelta(minutes=2, seconds=26), '/shutify/app/static/music/bensound-ukulele.mp3', '/static/music/bensound-ukulele.mp3', 2, 22), ('Tomorrow', 3, 3, 1, timedelta(minutes=4, seconds=54), '/shutify/app/static/music/bensound-tomorrow.mp3 ', '/static/music/bensound-tomorrow.mp3', 1, 15), ] for item in songs: song = Song.query.filter_by(title=item[0]).first() if song is None: song = Song( title=item[0], artist_id=item[1], album_id=item[2], genre_id=item[3], duration=item[4], file_path=item[5], file_url=item[6], track=item[7], num_plays=item[8], ) db.session.add(song) try: db.session.commit() except: db.session.rollback()
import pandas as pd from datetime import datetime from app import db from app.models import User, Album df = pd.read_csv('./app/input_files/favorites.txt', sep='\t') u = User.query.get(1) for i, r in df.iterrows(): dstr = r['Last Listen'].split('/') yr, mo, da = int(dstr[2]), int(dstr[0]), int(dstr[1]) if yr < 2000: yr += 2000 dt = datetime(yr, mo, da) # add album a = Album(title=r.Album, artist=r.Artist, year=r.Year, last_played=dt, rank=r.Rank, user_id=u.id) db.session.add(a) db.session.commit()
albums = pd.read_csv('albums.csv') joined = pd.merge(sample, albums, on='album_id', how='left') removed = joined[~joined['remove'].isna()] joined = joined[joined['remove'].isna()] # Check that the database contains all 8 expected genres genres = Genre.query.all() genre_names = [g.name for g in genres] all_genres = [ 'country', 'electronic', 'folk', 'indie', 'metal', 'pop', 'rap', 'rock' ] for g in all_genres: if g not in genre_names: db.session.add(Genre(name=g)) # Create mapping of genre name to id to assign albums a proper genre id genres = Genre.query.all() genre_map = {g.name: g.genre_id for g in genres} for album in joined.itertuples(): db.session.merge( Album(album_id=album.album_id, genre_id=genre_map.get(album.genre), prediction_id=list(genre_map.values())[random.randint(0, 7)], confidence=random.random() * 0.4, name=album.album[:60], artist=album.artist)) db.session.commit()