def get_artist_tracks_from_musicbrianz_api(artist): search_results = mb.search_artists(artist) result = search_results['artist-list'][0] genre = Artist.get_genre_from_musicbrainz_tag_list(result['tag-list']) for album_dict in mb.browse_releases(result['id'], includes=['recordings' ])['release-list']: album = Album.objects.create(name=album_dict['title'], artist=artist, slug=slugify(album_dict['title'])) for track_dict in album_dict['medium-list'][0]['track-list']: track = Track.objects.create(album=album, name=track_dict['recording']['title'], track_number=track_dict['position'], slug=slugify( track_dict['recording']['title'])) Artist.objects.create(track=track, artist=artist, genre=genre, slug=slugify(artist)) return Artist.objects.filter(artist=artist)
async def update_artist(artist_id: str, artist: ArtistEdition, username: str = auth): to_update = await mongo.find_one(artist_id, db_m) if to_update is not None: update_data = artist.dict(exclude_unset=True) update_model = Artist(**to_update).copy(update=update_data) result = await mongo.update_one(artist_id, classToDict(update_model), db_m) return result return 'Invalid Id'
def process_file(self, reader): for line in reader: artist = line[1] if not artist: self.stdout.write( self.style.WARNING('Data is invalid (empty). Skipped.')) continue # Check to see if artist is already in database. if Artist.objects.filter(name=artist).exists(): self.stdout.write( self.style.WARNING( f"Name: '{artist}' is already exists in the Artist table in database. Skipped." )) else: a = Artist(name=artist) a.save()
def import_artists(self, artists): for art in artists: try: artist = Artist.objects.get(id=art.get('personId')) except Artist.DoesNotExist: artist = Artist(id=art.get('personId')) artist.biography = self._clean_up_html(art.get( 'biography', '')) artist.first_name = art.get('firstName', '').strip() artist.last_name = art.get('lastName', '').strip() artist.salutation = art.get('salutation', '').strip() website = art.get('website', '') artist.website = website.strip() if website else "" if art.get('media'): artist.photo = u"images/{0}".format( art.get('media')[0]['fileName']) artist.save() instrument = Instrument.objects.get(id=art.get('personTypeId')) artist.instruments.add(instrument)
async def delete_artist_song(artist_id: str, song_id: str, username: str = auth): to_update = await mongo.find_one(artist_id, db_m) update_model = Artist(**to_update) if to_update is not None: if update_model.canciones is not None: cont=0 canciones_to_update = [] for c in update_model.canciones: if c.id != song_id: canciones_to_update.append(c) cont+=1 if cont == len(update_model.canciones): return 'Invalid Id for Cancion' update_data = {'canciones': canciones_to_update} updated = update_model.copy(update=update_data) result = await mongo.update_one(artist_id, classToDict(updated), db_m) return result else: return 'Do not find Canciones' return 'Invalid Id for Artista'
def import_artists(self, artists): for art in artists: try: artist = Artist.objects.get(id=art.get('personId')) except Artist.DoesNotExist: artist = Artist(id=art.get('personId')) artist.biography = self._clean_up_html(art.get('biography', '')) artist.first_name = art.get('firstName', '').strip() artist.last_name = art.get('lastName', '').strip() artist.salutation = art.get('salutation', '').strip() website = art.get('website', '') artist.website = website.strip() if website else "" if art.get('media'): artist.photo = u"images/{0}".format(art.get('media')[0]['fileName']) artist.save() instrument = Instrument.objects.get(id=art.get('personTypeId')) artist.instruments.add(instrument)
async def create_artist_song(artist_id: str, song: str, username: str = auth): to_update = await mongo.find_one(artist_id, db_m) update_model = Artist(**to_update) if to_update is not None: song_db = await mongo.find_many(update_model.nombre+' '+song, db_s) if song_db is not None: cancion = { 'id': song_db[0]['id'], 'cancion': song_db[0]['metadata']['cancion'], 'album': song_db[0]['metadata']['album'] } if update_model.canciones is not None: canciones_to_update = update_model.canciones canciones_to_update.append(ArtistSong(**cancion)) else: canciones_to_update = [] canciones_to_update.append(ArtistSong(**cancion)) update_data = {'canciones': canciones_to_update} updated = update_model.copy(update=update_data) result = await mongo.update_one(artist_id, classToDict(updated), db_m) return result return 'La canción no se encontró' return 'Invalid Id'
def getAlbumByName(request, name): try: Album.objects.get(name__icontains=name) albums = Album.objects.filter(name__icontains=name) data = { "results": list( albums.values("name", "album_id", "artist__name", "artist__artist_id")) } return JsonResponse(data) except ObjectDoesNotExist: response = requests.get('https://api.deezer.com/search/album?q=%s' % name) albums_data = response.json() if albums_data.get('total') == 0: return HttpResponse('No album according to URL param Name') else: album_artist = Artist.objects.filter( artist_id=albums_data['data'][0]['artist']['id']) if album_artist: album = Album(name=albums_data['data'][0]['title'], album_id=albums_data['data'][0]['id'], artist=album_artist.get()) album.save() return redirect('getAlbumByName', name=album.name) else: #Caso não exista o artist na nossa base, varre a API e cadastra o artista para instanciar o album artist_response = requests.get( 'https://api.deezer.com/artist/%s' % albums_data['data'][0]['artist']['id']) artists_data = artist_response.json() artist = Artist(name=artists_data['name'], artist_id=artists_data['id'], link=artists_data['link'], tracklist=artists_data['tracklist']) artist.save() return redirect('getAlbumByName', name=name)
def getAlbumById(request, id): try: Album.objects.get(album_id=id) albums = Album.objects.filter(album_id=id) data = { "results": list( albums.values("name", "album_id", "artist__name", "artist__artist_id")) } return JsonResponse(data) except ObjectDoesNotExist: response = requests.get('https://api.deezer.com/album/%s' % id) albums_data = response.json() if albums_data.get('error'): return HttpResponse('No album according to URL param ID') else: album_artist = Artist.objects.filter( artist_id=albums_data['contributors'][0]['id']) if album_artist: album = Album(name=albums_data['title'], album_id=albums_data['id'], artist=album_artist.get()) album.save() return redirect('getAlbumById', id=album.album_id) else: #Caso não exista o artist na nossa base, varre a API e cadastra o artista para instanciar o album artist_response = requests.get( 'https://api.deezer.com/artist/%s' % albums_data['contributors'][0]['id']) artists_data = artist_response.json() artist = Artist(name=artists_data['name'], artist_id=artists_data['id'], link=artists_data['link'], tracklist=artists_data['tracklist']) artist.save() return redirect('getAlbumById', id=album.album_id)
def make_artist_model_instances(self): artists = Artist.objects.bulk_create([ Artist(id=i, name=i, profile_image_url=f'{i}.jpeg', introduction=i, description=i) for i in range(1, 3) ]) types = Type.objects.bulk_create( [Type(id=i + 1, name=v) for i, v in enumerate(['화가', '사진가'])]) artist_types = ArtistType.objects.bulk_create( [ArtistType(artist_id=i + 1, type_id=i + 1) for i in range(2)]) return { "artists": artists, "types": types, "artist_types": artist_types, }
def handle(self, *args, **options): # import the scan_tool we will use spec = importlib.util.spec_from_file_location( 'scan_tool', Setting.objects.get(key='scan_tool').value) scan_tool = importlib.util.module_from_spec(spec) sys.modules[spec.name] = scan_tool spec.loader.exec_module(scan_tool) # new artists, songs and metadata are added by "admin" admin_id = User.objects.get(username='******').pk for path in options['paths']: # scan the uploaded file try: info = scan_tool.scan(path) except Exception as e: raise ValueError("Failed to parse uploaded file: %s" % str(e)) # also calculate the hash with open(path, 'rb') as f: filehash = hashlib.sha1(f.read()).digest() # construct song meta dict for adding new entries file_info = { 'file_type': info['file_type'], 'sample_rate': info['sample_rate'], 'channels': info['channels'], 'bit_rate': info['bit_rate'], 'duration': timedelta(seconds=info['duration']), 'hash': filehash } song_info = {} changed_fields = 'name filepath' if 'tags' in info: if 'title' in info['tags']: song_info['name'] = info['tags']['title'] else: song_info['name'] = path if 'album' in info['tags']: song_info['info'] = info['tags']['album'] changed_fields += ' info' if 'date' in info['tags']: song_info['date'] = datetime.strptime( info['tags']['date'], '%Y-%m-%d') changed_fields += ' release_date' if 'artist' in info['tags']: artist_name = info['tags']['artist'] changed_fields += ' artist' else: song_info['name'] = path artist_name = None # get the artist from the DB - if it doesn't exist, we need to create it if artist_name: try: artist = Artist.objects.get(name=artist_name) except Artist.DoesNotExist: artist = Artist(name=artist_name) artist.save() artist_meta = ArtistMeta(artist=artist, name=artist_name) artist_meta.save() else: artist = None # Everything is parsed. We're committed to import now! # create the song and meta, and attach the song to it. with open(path, 'rb') as f: imported_filename = default_storage.save( upload_to(None, path), f) # file has been imported to our local filesystem # now we can create an SongFile object around it song_file = SongFile(filepath=imported_filename, **file_info) song_file.save() # add the Song song = Song(**song_info) song.song_file = song_file song.save() song.artist.set([artist]) song_meta = SongMeta(song=song, reviewed=True, accepted=True, changed_fields=changed_fields, submitter_id=admin_id, song_file=song_file, **song_info) song_meta.save() song_meta.artist.set([artist]) self.stdout.write( self.style.SUCCESS('Successfully imported file "%s"' % path))
def getTrackById(request, id): try: Track.objects.get(track_id=id) tracks = Track.objects.filter(track_id=id) data = { "results": list(tracks.values("name", "track_id", "album__album_id")) } return JsonResponse(data) except ObjectDoesNotExist: response = requests.get('https://api.deezer.com/track/%s' % id) tracks_data = response.json() if tracks_data.get('error'): return HttpResponse('No track according to URL param ID') else: album_artist = Artist.objects.filter( artist_id=tracks_data['artist']['id']) track_album = Album.objects.filter( album_id=tracks_data['album']['id']) if album_artist and track_album: track = Track(name=tracks_data['title'], track_id=tracks_data['data']['id'], album=track_album.get()) track.save() return redirect('getTrackByName', name=tracks_data['data']['title']) elif album_artist and not track_album: album_response = requests.get( 'https://api.deezer.com/album/%s' % tracks_data['data'][0]['album']['id']) albums_data = album_response.json() album = Album(name=albums_data['title'], album_id=albums_data['id'], artist=album_artist.get()) album.save() track = Track(name=tracks_data['title'], track_id=tracks_data['id'], album=album) track.save() return redirect('getTrackByName', name=tracks_data['title']) else: artist_response = requests.get( 'https://api.deezer.com/artist/%s' % tracks_data['artist']['id']) artists_data = artist_response.json() artist = Artist(name=artists_data['name'], artist_id=artists_data['id'], link=artists_data['link'], tracklist=artists_data['tracklist']) artist.save() album_response = requests.get( 'https://api.deezer.com/album/%s' % tracks_data['album']['id']) albums_data = album_response.json() album = Album(name=albums_data['title'], album_id=albums_data['id'], artist=artist) album.save() track = Track(name=tracks_data['title'], track_id=tracks_data['id'], album=album) track.save() return redirect('getTrackByName', name=tracks_data['title'])
def addTrack(request): N = 27 pi = ''.join( random.choice(string.ascii_uppercase + string.digits) for _ in range(N)) if request.GET.get('name') and request.GET.get('album_id'): try: album = Album.objects.get(album_id=request.GET.get('album_id')) if album: tracks = album.track_set.all() track_list = [] x = 0 while x < (len(tracks)): single_track = tracks[x].name track_list.append(single_track) x += 1 if request.GET.get('name') in track_list: return redirect('getTrackByName', name=request.GET.get('name')) else: track = Track(name=request.GET.get('name'), track_id=pi, album=album) track.save() return redirect('getTrackByName', name=request.GET.get('name')) except ObjectDoesNotExist: album_response = requests.get('https://api.deezer.com/album/%s' % request.GET.get('album_id')) albums_data = album_response.json() if not albums_data.get('error'): try: Artist.objects.get( artist_id=albums_data['contributors'][0]['id']) artist = Artist.objects.get( artist_id=albums_data['contributors'][0]['id']) if artist: album = Album(name=albums_data['title'], album_id=albums_data['id'], artist=artist) album.save() track = Track(name=request.GET.get( 'name', track_id=pi, album=album)) track.save() return redirect('getTrackByName', name=request.GET.get('name')) except ObjectDoesNotExist: artist_response = requests.get( 'https://api.deezer.com/artist/%s' % albums_data['contributors'][0]['id']) artists_data = artist_response.json() artist = Artist(name=artists_data['name'], artist_id=artists_data['id'], link=artists_data['link'], tracklist=artists_data['tracklist']) artist.save() album = Album(name=albums_data['title'], album_id=albums_data['id'], artist=artist) album.save() track = Track( name=request.GET.get('name', track_id=pi, album=album)) track.save() return redirect('getTrackByName', name=request.GET.get('name')) else: return HttpResponse( 'Album is not registered neither in API or Database.') return HttpResponse( 'The {{name}} param and the {{album_id}} param is required to associate track to album' )
def addAlbum(request): N = 27 pi = ''.join( random.choice(string.ascii_uppercase + string.digits) for _ in range(N)) if request.GET.get('name'): try: Album.objects.get(name=request.GET.get('name')) albums = Album.objects.filter(name=request.GET.get('name')) data = { "results": list( albums.values("name", "album_id", "artist__name", "artist__artist_id")) } return JsonResponse(data) except ObjectDoesNotExist: if request.GET.get('artist_id'): album_list_response = requests.get( 'https://api.deezer.com/artist/%s/albums' % request.GET.get('artist_id')) album_data = album_list_response.json() album_list = [] x = 0 if not album_data['error']: while x < (len(album_data['data'])): album_title = album_data['data'][x]['title'] album_list.append(album_title) x += 1 if request.GET.get('name') in album_list: return redirect('getAlbumByName', name=request.GET.get('name')) else: artist = Artist.objects.filter( artist_id=request.GET.get('artist_id')) if artist: album = Album(name=request.GET.get('name'), album_id=pi, artist=artist.get()) album.save() return redirect('getAlbumByName', name=request.GET.get('name')) else: artist = Artist.objects.get( artist_id=request.GET.get('artist_id')) if not artist: artist_response = requests.get( 'https://api.deezer.com/artist/%s' % request.GET.get('name')) artists_data = artist_response.json() artist = Artist(name=artists_data['name'], artist_id=artists_data['id'], link=artists_data['link'], tracklist=artists_data['tracklist']) artist.save() album = Album(name=request.GET.get('name'), album_id=pi, artist=artist.get()) album.save() return redirect('getAlbumByName', name=request.GET.get('name')) else: album = Album(name=request.GET.get('name'), album_id=pi, artist=artist) album.save() return redirect('getAlbumByName', name=request.GET.get('name')) else: return HttpResponse( 'The artist_id param is required to associate album to artist' ) else: return HttpResponse( 'The {{name}} param and the {{artist_id}} param is required to associate album to artist' )