def move_audio(audio, library, verbose, dry_run): """ Copy audio to library. """ try: # tag values are stored in lists so we unpack them here: tags = { k:v[0] for (k,v) in read_tags(audio).iteritems() } # TODO handle multiple types of exceptions here. except Exception as e: print(type(e)) print(e.message) print("Error: {} has no ID3 tags. Moving on to next file.".format(audio)) return # TODO this is ugly! settings = load_yaml('settings.yaml') tags['ext'] = os.path.splitext(audio)[1] tags = dict(tags.items() + settings.items()) dest = settings['naming_format'].format(**tags) if verbose or dry_run: print('Copying {} to {}.'.format(audio, dest)) if not dry_run: shutil.copy2(audio, dest) if not compare_files(audio, dest): print('Error in copying {} from {}. Moving on to next ' \ 'file'.format(audio, dest))
def searchbyalbum(request): context = RequestContext(request) results=[] if request.method == 'GET': name=request.GET['name'] r = Picture.objects.all() for item in r: mp3 = read_tags(settings.MEDIA_ROOT + item.file.name) if name in str(mp3['album'][0]).lower(): results.append(item) no_of_results = len(results) dict2={'results': results,'playlist':playlist,'no_of_results' : no_of_results} return render_to_response('playmusic/searchresults.html',dict2,context)
def tags(name): """ Returns tags in the audio file as `dict`. It converts tags returned by ``mutagenwrapper.read_tags`` by unwrapping single valued items (i.e. without enclosing lists) and removing `encodedby` tag. To read unmodified, but still normalized tags, use ``mutagenwrapper.read_tags``. For unmodified and unnormalized tags, use the ``mutagen`` library. """ if mutagenwrapper is None: raise ImportError('mutagenwrapper is required to read tags') return {key: _unwrap(value) for key, value in mutagenwrapper.read_tags(name).iteritems() if key != 'encodedby'}
def get_albumart(): file = request.args.get('file') if not file: abort(400) # remove image extensions file = os.path.splitext(file)[0] path = get_folder('music') + '/' + file try: data, mimetype = get_albumart_data(read_tags(path)) except: data, mimetype = None, None if not data or not mimetype: abort(404) resp = Response(data, status=200, mimetype=mimetype) return resp
def tags(name): """ Returns tags in the audio file as `dict`. It converts tags returned by ``mutagenwrapper.read_tags`` by unwrapping single valued items (i.e. without enclosing lists) and removing `encodedby` tag. To read unmodified, but still normalized tags, use ``mutagenwrapper.read_tags``. For unmodified and unnormalized tags, use the ``mutagen`` library. """ if mutagenwrapper is None: raise ImportError('mutagenwrapper is required to read tags') return { key: _unwrap(value) for key, value in mutagenwrapper.read_tags(name).iteritems() if key != 'encodedby' }
def tags(name): """Returns tags in the audio file as a :class:`dict`. Its return value is the same as ``mutagenwrapper.read_tags``, except that single valued items (lists with length 1) are unwrapped and ``encodedby`` tag is removed. To read unmodified, but still normalized tags, use ``mutagenwrapper.read_tags``. For raw tags, use the ``mutagen`` library. """ if mutagenwrapper is None: raise ImportError('mutagenwrapper is required to read tags') if not is_supported_format(name): raise UnsupportedFileError(name + ' is not a supported audio file') if get_extension(name) == 'wav': return {} return dict((key, _unwrap(value)) for key, value in mutagenwrapper.read_tags(name).iteritems() if key != 'encodedby')
def build_songs(category_id): try: category_folder = list_folders(get_folder('music'))[int(category_id)] category_path = get_folder('music/' + category_folder) audio_files = list_files(category_path, ['flac', 'm4a', 'mp3']) except IndexError: audio_files = [] songs = [] for idx, audio_file in enumerate(audio_files): path = category_path + '/' + audio_file file = category_folder + '/' + audio_file # harcoded urls are needed becaus url_for() it's too slow song_url = request.url_root + 'get-song?file=' + \ urllib.quote(file.encode('utf8')) try: tags = read_tags(path) title = tags.find('title') album = tags.find('album') author = tags.find('artist') except: tags = None title = None album = None author = None albumart_mime = get_albumart_data(tags)[1] if albumart_mime: extension = albumart_mime.replace('image/', '') albumart_file = file + '.' + extension albumart_url = request.url_root + 'get-albumart?file=' + \ urllib.quote(albumart_file.encode('utf8')) else: extension = None albumart_file = None albumart_url = None songs.append({ 'id': idx, 'radio_id': category_id, 'filename': audio_file, 'title': title, 'album': album, 'author': author, 'albumart_filename': albumart_file, 'songUrl': song_url, 'albumartUrl': albumart_url }) return songs
def clean(self): file_path = self.file_field.path tags = mutagenwrapper.read_tags(file_path) self.title = tags.find('title', 'unknown') artist_name = tags.find('artist', 'unknown') artist, artist_created = Artist.objects.get_or_create(name=artist_name) album_artist_name = tags.find('albumartist', artist_name) album_artist, album_artist_created = Artist.objects.get_or_create(name=album_artist_name) album, album_created = Album.objects.get_or_create(name=tags.find('album', 'unknown'), album_artist=album_artist) artwork = tags.find('pictures') if album_created: album.number_of_tracks = tags.find('tracktotal') album.number_of_discs = tags.find('disctotal') if artwork: album.artwork = AlbumArtwork.add(artwork, album) album.save() if (not album.artwork) and artwork: album.artwork = AlbumArtwork.add(artwork, album) album.save() if not artist.artwork: if album.artwork: artist.artwork = ArtistArtwork.add_existing_artwork(album.artwork.image, artist) artist.save() if (album_artist.pk != artist.pk) and (not album_artist.artwork): if album.artwork: album_artist.artwork = ArtistArtwork.add_existing_artwork(album.artwork.image, artist) album_artist.save() self.artist = artist self.album = album self.year = tags.find('year', 'unknown') self.track_number = tags.find('tracknumber') self.disc_number = tags.find('discnumber') self.save()
def read_tags(tmpdir, name): p = tmpdir.join(os.path.basename(name)) p.write(read(name), 'wb') return mutagenwrapper.read_tags(p.strpath)
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))