def set_image(self, image): """Replaces all embedded images by the passed image""" with translate_errors(): tag = FLAC(self["~filename"]) try: data = image.read() except EnvironmentError as e: raise AudioFileError(e) pic = Picture() pic.data = data pic.type = APICType.COVER_FRONT pic.mime = image.mime_type pic.width = image.width pic.height = image.height pic.depth = image.color_depth tag.add_picture(pic) with translate_errors(): tag.save() # clear vcomment tags super(FLACFile, self).clear_images() self.has_images = True
def setSortTags(path): ext = os.path.splitext(path)[1].lower() meta = None try: if ext == '.mp3': meta = MP3(path) elif ext == '.m4a': meta = MP4(path) elif ext == '.flac': meta = FLAC(path) else: return except: pass if meta: tagsToProcess = ('ALBUM', 'ALBUMARTIST', 'ARTIST', 'TITLE') save = False try: for tag in tagsToProcess: processed = checkTagMakeSort(path, meta, tag) if (processed): save = True if save: meta.save() except: pass
def check_flac_tags(full_path, e): t = {} # "proper" tags tags = FLAC(full_path) unallowed = set(tags.keys()).difference(flac_allow) if unallowed: for item in unallowed: e.append("Unallowed tag: '" + item + "' - remove") # "minimal" tags for item in 'album', 'tracknumber', 'title', 'date': t[item] = tags[item][0] # Handle multiple artist tags in single track if len(tags['artist']) > 1: t['artist'] = ", ".join(tags['artist']) else: t['artist'] = tags['artist'][0] # "optional" tags for item in 'tracktotal', 'genre', 'albumartist', 'discnumber', 'disctotal': if item in tags: t[item] = tags[item][0] else: t[item] = None return t, e
def flac_read(fpath): audio = FLAC(fpath) return uni({ 'artist': audio.get('artist', [None])[0], 'album': audio.get('album', [None])[0], 'title': audio.get('title', [None])[0] })
class FlacStripper(MutagenStripper): """ Represent a Flac audio file """ def _create_mfile(self): self.mfile = FLAC(self.filename) def remove_all(self): """ Remove the "metadata" block from the file """ super(FlacStripper, self).remove_all() self.mfile.clear_pictures() self.mfile.save() return True def is_clean(self): """ Check if the "metadata" block is present in the file """ return super(FlacStripper, self).is_clean() and not self.mfile.pictures def get_meta(self): """ Return the content of the metadata block if present """ metadata = super(FlacStripper, self).get_meta() if self.mfile.pictures: metadata['picture:'] = 'yes' return metadata
def test_two_invalid(tmpdir): """Test when two FLAC files have invalid tags.""" flac_dir = tmpdir.mkdir('flac') flac_files = [] # One. flac = flac_dir.join('Artist2 - 202 - Album - 01 - Title.flac').ensure(file=True) with open(os.path.join(os.path.dirname(__file__), '1khz_sine.flac'), 'rb') as f: flac.write(f.read(), 'wb') tags = FLAC(str(flac.realpath())) tags.update(dict(artist='Artist2', date='2012', album='Album', tracknumber='01', title='Title')) tags.save() flac_files.append(str(flac.realpath())) # Two. flac = flac_dir.join('Artist - 2014 - Album - 01 - Title.flac').ensure(file=True) with open(os.path.join(os.path.dirname(__file__), '1khz_sine.flac'), 'rb') as f: flac.write(f.read(), 'wb') tags = FLAC(str(flac.realpath())) tags.update(dict(artist='Artist2', date='2014', album='Album', tracknumber='01', title='Title')) tags.save() flac_files.append(str(flac.realpath())) # Test. a_messages = find_inconsistent_tags(flac_files, True, True) e_messages = { flac_files[0]: ["Filename date not four digits."], flac_files[1]: ["Artist mismatch: Artist != Artist2"], } assert e_messages == a_messages
def test_delete_multiple(self): # on delete we delete both f = FLAC(self.filename) f.delete() assert len(f.tags) == 0 f = FLAC(self.filename) assert f.tags is None
def test_one_valid_two_invalid(tmpdir): """Test when one FLAC file is fully valid and another one isn't.""" flac_dir = tmpdir.mkdir('flac') flac_files = [] # Valid. flac = flac_dir.join('Artist2 - 2012 - Album - 01 - Title.flac').ensure(file=True) with open(os.path.join(os.path.dirname(__file__), '1khz_sine.flac'), 'rb') as f: flac.write(f.read(), 'wb') tags = FLAC(str(flac.realpath())) tags.update(dict(artist='Artist2', date='2012', album='Album', tracknumber='01', title='Title')) tags.save() flac_files.append(str(flac.realpath())) # Invalid. flac = flac_dir.join('Artist - 2014 - Album - 01 - Title.flac').ensure(file=True) with open(os.path.join(os.path.dirname(__file__), '1khz_sine.flac'), 'rb') as f: flac.write(f.read(), 'wb') tags = FLAC(str(flac.realpath())) tags.update(dict(artist='Artist2', date='2014', album='Album', tracknumber='01', title='Title')) tags.save() flac_files.append(str(flac.realpath())) # Test. a_messages = find_inconsistent_tags(flac_files, True, True) e_messages = {flac_files[1]: [ "Artist mismatch: Artist != Artist2", ]} assert e_messages == a_messages
def test_largest_valid(self): f = FLAC(self.filename) pic = Picture() pic.data = b"\x00" * (2 ** 24 - 1 - 32) self.assertEqual(len(pic.write()), 2 ** 24 - 1) f.add_picture(pic) f.save()
def test_force_shrink(self): self.test_force_grow() f = FLAC(self.NEW) f["faketag"] = "foo" f.save() f = FLAC(self.NEW) self.failUnlessEqual(f["faketag"], ["foo"])
def setImage(self, song): audio = FLAC(song.get("~filename", "")) if len(self.imgFiles) <= 0: return for p in self.imgFiles: try: audio.add_picture(p) except: printError() return False audio.save() ## and now count the images count = "0" ## if file has no images -> set to 0 if (audio.pictures is None) or (len(audio.pictures) <= 0): pass else: count = str(len(audio.pictures)) if not "pictures" in song: song["pictures"] = count if song["pictures"] <> count: song["pictures"] = count app.window.emit("artwork-changed", [song]) return
class Id3tool: ''' class to read/write mp3 tags ''' def __init__(self, fn): ''' allow throw if file not supported ''' if fnmatch.fnmatch(fn, '*.ogg'): self.tag_obj = OggVorbis(fn) elif fnmatch.fnmatch(fn, '*.flac'): self.tag_obj = FLAC(fn) else: self.tag_obj = EasyID3(fn) def save(self): self.tag_obj.save() def readTag(self, tag): if self.tag_obj: tmp = self.tag_obj.get(unicode(tag)) return tmp[0] if tmp else '' else: return '' def writeTag(self, tag, val): self.tag_obj[unicode(tag)] = unicode(val)
def getsubmission(tfile): data = open(tfile).read() torrent = decode(data) tname = torrent['info']['name'] for file in torrent["info"]["files"]: name = "/".join(file["path"]) flac_re = re.compile(".flac") if flac_re.search(name) != None: flacname=name log_re = re.compile(".log") if log_re.search(name) !=None: logname=name fpath = os.path.join(tname,flacname) lpath = os.path.join(tname,logname) audio = FLAC(fpath) print audio.keys() if not audio.has_key('musicbrainz_albumid'): print "ReleaseID tag is not set. Has this flac been tagged by picard?" return(-1) albumid = audio['musicbrainz_albumid'][0] print albumid q = ws.Query() try: inc = ws.ReleaseIncludes(artist=True, releaseEvents=True, labels=True, discs=True, tracks=True) release = q.getReleaseById(albumid, inc) except ws.WebServiceError, e: print 'Error:', e return(-1)
def tag(self): if self.type == 'Free Lossless Audio Codec': f = FLAC(self.name) tags = CUE_META.flac_tags(self.track_nr) for t in tags[0]: f[t] = tags[0][t] f.save()
def write_field(self, file, field, value, bypassdbwrite=False): filename, extension = os.path.splitext(file) if extension.upper() == '.MP3': # Try to open the ID3 tags try: audio = ID3(file) except mutagen.id3.ID3NoHeaderError: # Save a blank ID3 header first audio = ID3() id3field = self.MAP_ID3_FIELDS[field] fieldtype, unused, fieldname = id3field.partition(':') gentag = getattr(mutagen.id3, fieldtype) audio[id3field] = gentag(encoding=3, desc=u'%s' % fieldname, text=value) #audio['TXXX:TAG'] = TXXX(encoding=3, desc=u'TAG', text=tags) elif extension.upper() == '.FLAC': audio = FLAC(file) audio[self.MAP_FLAC_FIELDS[field]] = value audio.save(file) print "[LIBRARY] Field '%s' written in file %s" % (field, os.path.basename(file)) # Update DB if needed if file in self.map_track_info: self.map_track_info[file][field] = value if not bypassdbwrite: self.save_database()
def main(args): """ """ # This is nonsense, don't need to pass that argument twice scanner = scan.Scanner() if not scanner.scan_album(args.album): sys.stderr.write('Invalid Album!\n') sys.exit(1) # Construct an album representation # (This function will be moved to the lib) m = const.REGEX_ALBUM_FOLDER.match(args.album).groupdict() if not m: # A bit reduntant, but better safe than sorry sys.stderr.write("Could not read album folder\n") sys.exit(1) files = map(lambda fn: os.path.join(args.album, fn), sorted(filter(const.REGEX_TRACK_FILENAME.match, os.listdir(args.album) ) ) ) show = '' for fn in files: audio = FLAC(fn) # Maybe create a util function for this purpose audio_dict = dict([(k,v[0]) for k,v in audio.items()]) show += TPL_TRACK_SHOW.format(**audio_dict) head = TPL_ALBUM_SHOW.format(**audio_dict) show = head + TPL_SEPARATOR(len(head)-1) + show print show.strip('\n')
def _loadTags(self): try: audio = FLAC() audio.load(self.uri) return audio.tags except Exception, e: return None
def media_info(f): aid_re = re.compile("brainz.*album.*id",re.I) has_info = 0 ext = os.path.splitext(f)[-1] if ext == ".mp3": has_info = 1 info = ID3(f) format = "MP3" if ext == ".flac": has_info = 1 info = FLAC(f) format = "FLAC" if ext == ".ogg": has_info = 1 info = OggVorbis(f) format = "OGG" if not has_info: return {} for k in info.keys(): if re.search(aid_re,k) != None: aid = info[k] if type(aid) ==mutagen.id3.TXXX: aid = aid.__unicode__() if type(aid) == type([0]): aid = aid[0] info_d = {} info_d['mbid'] = aid return info_d
def test_write_reread(self): flac = FLAC(self.NEW) del(flac["artist"]) flac.save() flac2 = FLAC(self.NEW) self.failUnlessEqual(flac["title"], flac2["title"]) data = open(self.NEW, "rb").read(1024) self.failIf("Tunng" in data)
def write_genre(self, file_path, file_ext, genre): '''write genre to a single file''' if file_ext == '.flac': tag = FLAC(file_path) elif file_ext == '.mp3': tag = EasyID3(file_path) tag['genre'] = genre tag.save()
def flac_write_tags(self, path, tag_type, input_string): try: flac_audio = FLAC(path) #Reading tags except mutagen.flac.FLACNoHeaderError: print ("%r is not a valid FLAC file") \ % (path.encode(sys.stdout.encoding or "utf-8", "replace"), ) return flac_audio[tag_type] = input_string flac_audio.save()
def copy_id3tag(src, des): from subprocess import call f = FLAC(src) args = ["neroAacTag", des] for key in f.keys(): args.extend([_rectify(key) + "=" + f[key][0],]) print args call(args)
def test_write_changetitle(self): f = FLAC(self.NEW) if PY3: self.assertRaises(ValueError, f.__setitem__, b'title', b"A New Title") else: f[b'title'] = b"A New Title" f.save() f = FLAC(self.NEW) self.failUnlessEqual(f[b"title"][0], b"A New Title")
def test_write_changetitle_unicode_key(self): f = FLAC(self.NEW) f[u"title"] = b"A New Title" if PY3: self.assertRaises(ValueError, f.save) else: f.save() f = FLAC(self.NEW) self.failUnlessEqual(f[u"title"][0], b"A New Title")
def test_write_changetitle_unicode_value(self): f = FLAC(self.NEW) if PY3: self.assertRaises(ValueError, f.__setitem__, b'title', u"A Unicode Title \u2022") else: f[b'title'] = u"A Unicode Title \u2022" f.save() f = FLAC(self.NEW) self.failUnlessEqual(f[b"title"][0], u"A Unicode Title \u2022")
def handle_audio_file(audio_file): print('Handling audio file', audio_file) extension = os.path.splitext(os.path.basename(audio_file))[1] if extension == '.mp3': mp3 = MP3(audio_file, ID3=ID3) print(list(dict(mp3).keys())) if not regex_list(dict(mp3).keys(), re.compile('[Aa][Pp][Ii][Cc].*')): artist = mp3['TPE1'][0] album = mp3['TALB'][0] cover_data = open(get_cover_art(artist, album, audio_file), mode='rb') apic = APIC() apic.encoding = 3 apic.mime = 'image/jpg' apic.type = PictureType.COVER_FRONT apic.desc = u'Cover' apic.data = cover_data.read() cover_data.close() print('Adding cover art', cover_data.name, '->', audio_file) mp3['APIC'] = apic mp3.save() else: print(audio_file, 'already has cover artwork.') elif extension == '.m4a' or extension is '.aac': m4a = MP4(audio_file) print(list(dict(m4a).keys())) if 'covr' not in m4a: artist = m4a['\xa9ART'][0] album = m4a['\xa9alb'][0] cover_data = open(get_cover_art(artist, album, audio_file), mode='rb') covr = MP4Cover() covr.imageformat = AtomDataType.JPEG covr.data = cover_data.read() cover_data.close() print('Adding cover art', cover_data.name, '->', audio_file) m4a['covr'] = [covr] m4a.save() else: print(audio_file, 'already has cover artwork.') elif extension == '.flac': flac = FLAC(audio_file) print(list(dict(flac).keys())) if not flac.pictures: artist = flac['artist'][0] album = flac['album'][0] cover_data = open(get_cover_art(artist, album, audio_file), mode='rb') picture = Picture() picture.type = 3 picture.mime = 'image/jpg' picture.desc = u'Cover' picture.data = cover_data.read() cover_data.close() print('Adding cover artwork', cover_data.name, '->', audio_file) flac.add_picture(picture) flac.save() else: print(audio_file, 'already has cover artwork.') move_or_overwrite(audio_file, dest_audio, os.path.join(dest_audio, os.path.basename(audio_file)))
def _tag(self): w = FLAC(self.track_path) for k, v in self.tags.items(): w[k] = v w.save() self.stop()
def test_delete_id3(self): id3 = ID3() id3.add(TIT2(encoding=0, text='id3 title')) id3.save(self.NEW, v1=2) f = FLAC(self.NEW) f['title'] = 'vc title' f.save(deleteid3=True) self.failUnlessRaises(ID3NoHeaderError, ID3, self.NEW) f = FLAC(self.NEW) self.failUnlessEqual(f['title'], ['vc title'])
def getFlacLyrics(filename, getlrc): try: tags = FLAC(filename) if tags.has_key('lyrics'): lyr = tags['lyrics'][0] match1 = re.compile('\[(\d+):(\d\d)(\.\d+|)\]').search(lyr) if (getlrc and match1) or ((not getlrc) and (not match1)): return lyr except: return None
def flac(file_path): audio = FLAC(file_path) print "p p r i n t for %s" % file_path audio.pprint() print "p p r i n t" print audio length = audio.info.length #bitrate = audio.info.bitrate bitrate = 0 return length, bitrate
def add_flac_image_set(self,filename, images): audio = FLAC(filename) if self.replace_images: audio.clear_pictures() for img in images: self.add_flac_cover(audio, img['file'], desc=img['desc'], file_type=img['type']) print(f'{filename} images updated') audio.save()
def tag_flac(file, path, d, album, istrack=True): audio = FLAC(file) audio["TITLE"] = d["title"] # TRACK TITLE audio["TRACKNUMBER"] = str(d["track_number"]) # TRACK NUMBER try: audio["COMPOSER"] = d["composer"]["name"] # COMPOSER except KeyError: pass try: audio["ARTIST"] = d["performer"]["name"] # TRACK ARTIST except KeyError: if istrack: audio["ARTIST"] = d["album"]["artist"]["name"] # TRACK ARTIST else: audio["ARTIST"] = album["artist"]["name"] if istrack: audio["GENRE"] = ", ".join(d["album"]["genres_list"]) # GENRE audio["ALBUMARTIST"] = d["album"]["artist"]["name"] # ALBUM ARTIST audio["TRACKTOTAL"] = str(d["album"]["tracks_count"]) # TRACK TOTAL audio["ALBUM"] = d["album"]["title"] # ALBUM TITLE audio["YEAR"] = d["album"]["release_date_original"].split("-")[0] else: audio["GENRE"] = ", ".join(album["genres_list"]) # GENRE audio["ALBUMARTIST"] = album["artist"]["name"] # ALBUM ARTIST audio["TRACKTOTAL"] = str(album["tracks_count"]) # TRACK TOTAL audio["ALBUM"] = album["title"] # ALBUM TITLE audio["YEAR"] = album["release_date_original"].split("-")[0] # YEAR audio.save() title = sanitize_filename(d["title"]) try: os.rename(file, "{}/{:02}. {}.flac".format(path, d["track_number"], title)) except FileExistsError: print("File already exists. Skipping...")
def setmusiclength(self): #important function on a player (also hard to do) if self.currentsong.endswith('.mp3') == True: self.song = MP3(self.currentsong) self.songinfo = ID3(self.currentsong) self.songlength = self.song.info.length self.songround = round(self.songlength) self.songmins, self.songsecs = divmod(self.songround, 60) self.songmins = str(self.songmins).zfill(2) self.songsecs = str(self.songsecs).zfill(2) self.progress_label_2.config(text=str(self.songmins) + ':' + str(self.songsecs)) try: self.songname.config(text=self.songinfo['TIT2'].text[0]) self.artistname.config(text=self.songinfo['TPE1'].text[0]) self.albumname.config(text=self.songinfo['TALB'].text[0]) except: self.songname.config(text=self.currentsong) self.artistname.config(text='failed to read metadata') self.albumname.config(text='failed to read metadata') if self.currentsong.endswith('.flac') == True: self.song = FLAC(self.currentsong) self.songlength = self.song.info.length self.songround = round(self.songlength) self.songmins, self.songsecs = divmod(self.songround, 60) self.songmins = str(self.songmins).zfill(2) self.songsecs = str(self.songsecs).zfill(2) self.progress_label_2.config(text=str(self.songmins) + ':' + str(self.songsecs)) self.music_player_scale.config(from_=0, to=self.songlength) try: self.songname.config(text=self.song['TITLE']) self.artistname.config(text=self.song['ARTIST']) self.albumname.config(text=self.song['ALBUM']) except: self.songname.config(text=self.currentsong) self.artistname.config(text='failed to read metadata') self.albumname.config(text='failed to read metadata') if self.currentsong.endswith('.ogg') == True: self.song = WAVE(self.currentsong) self.songlength = self.song.info.length self.songround = round(self.songlength) self.songmins, self.songsecs = divmod(self.songround, 60) self.songsecs = str(self.songsecs).zfill(2) self.progress_label_2.config(text=str(self.songmins) + ':' + str(self.songsecs))
def fetchfile(request): action = request.POST['action'] dir = request.POST['dir'] file = request.POST['file'] cat = request.POST['cat'] song_link = request.POST['song_link'] quality = request.POST['quality'] post_url = "http://hqzone.telugump3z.net/" + str(action) post_data = {"dir": dir, "file": file, "cat": cat} headers = { "User-Agent": "Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30.", "Referer": song_link} req3 = requests.post(post_url, headers=headers, data=post_data) flac_tags = {} #For cat = m4a (Lossless) if cat=="itune": with open('songs/' + cat + '.m4a', 'wb') as h: for block in req3.iter_content(1024): h.write(block) fname = "songs/" + cat + ".m4a" file = File(fname) # mutagen can automatically detect format and type of tags artwork = file.tags['covr'][0] # access APIC frame and grab the image with open("songs/albumart" + cat + ".jpg", 'wb') as img: img.write(artwork) # write artwork to new image elif cat=="flac": with open('songs/' + cat + '.flac', 'wb') as h: for block in req3.iter_content(1024): h.write(block) fname = "songs/" + cat + ".flac" file = FLAC(fname) # mutagen can automatically detect format and type of tags for p in file.pictures: with open("songs/albumart" + cat + ".jpg", 'wb') as img: img.write(p.data) # write artwork to new image flac_tags = {'song_title':file.tags['TITLE'][0],'song_artist':file.tags['ARTIST'][0],'song_album':file.tags['ALBUM'][0]} else: with open('songs/'+cat + '.mp3', 'wb') as h: for block in req3.iter_content(1024): h.write(block) fname = "songs/"+cat+".mp3" file = File(fname) # mutagen can automatically detect format and type of tags artwork = file.tags['APIC:'].data # access APIC frame and grab the image with open("songs/albumart"+cat+".jpg", 'wb') as img: img.write(artwork) # write artwork to new image '''f = open(fname, "rb") response = HttpResponse() response.write(f.read()) response['Content-Type'] = 'audio/mp3' response['Content-Length'] = os.path.getsize(fname) return response''' return render(request,'music/player.html',{'filename':"/"+fname,'album_art_location':"/songs/albumart"+cat+".jpg",'flac_tags':flac_tags})
def parse_flac(cls, filename): # FLAC() creates a FLAC object that can be conveniently converted into a dictionary audio = FLAC(cls.mediadir + filename) d = dict(audio) # All values in the dict are further stored inside lists; this removes that unnecessary layer for key in d: d[key] = d[key][0] # If a composer tag doesn't exist, create one with a blank string if not 'composer' in d: d['composer'] = '' return d
def add_words_to_db(): print("reading files to database") for i, file in enumerate(os.listdir(AUDIO_DIR)): if file.endswith(".flac"): WORDS.insert({ "word": FLAC(os.path.join(AUDIO_DIR, file))['title'][0], "pronunciation": FILES.put(open(AUDIO_DIR_NAME + '/' + file, 'rb'), file_name=file) }) if (i == 5): break print("Done.")
def TaggerWriteNone(files): print(style.red(ENV_ERROR_DISCOGS_NULL)) for file in files: try: file_extension = file.rsplit('.', 1)[1] f = None if file_extension == 'flac': f = FLAC(file) if file_extension == 'mp3': f = EasyID3(file) f['custom'] = ENV_TAGGING_TODO f.save() print(f['tracknumber'][0] + ' done') except: print(style.red(ENV_ERROR_TAGGING)) continue
def read_flac_tags(song, path): # album, artist, title, genre # tracknumber: '0x' # alternative: albumartist audio = FLAC(path) song[Song.artist] = get_str(audio, 'artist') song[Song.album] = get_str(audio, 'album') song[Song.title] = get_str(audio, 'title') song[Song.genre] = get_str(audio, 'genre') song[Song.year] = get_int(audio, 'year', '-') song[Song.album_index] = get_int(audio, 'tracknumber', '/') song[Song.length] = int(audio.info.length)
def songChanged(self, media): # filepath = self.player.media().canonicalUrl().path() filepath = media.canonicalUrl().path() tag = FLAC(filepath) for pic in tag.pictures: pix = QPixmap() pix.loadFromData(pic.data) self.ui.albumart.setPixmap(pix.scaled(100, 100, Qt.KeepAspectRatio)) self.ui.statusbar.showMessage('Now playing: ' + tag['title'][0] + ' by ' + tag['artist'][0]) self.player.play()
def _tag_flac(self, file): """ Tag Flac file only called from `track.tag()` """ tagger = Tagger(self, '.flac') tag = FLAC(file) tag.delete() for tag_obj in tagger.tag_map: tag[tag_obj.key] = str(tag_obj.value) # image if cc.tag_cover and self.album.picture_url is not None: cover_data = self.get_cover_data() if cover_data: img = Picture() img.type = 3 img.data = cover_data tag.clear_pictures() tag.add_picture(img) else: log.warning(f'No Cover for {self}') tag.save()
def artist(self): if self.mtype == "mp3": audio = ID3(self.path) return audio['TPE1'].text[0] elif self.mtype == "flac": artistList = [] audio = FLAC(self.path) for tag in audio.tags: if (tag[0] == 'ARTIST' or tag[0] == 'Artist'): artistList.append(tag[1].replace('\x00', '')) #部分结尾有谜之字符 return ("/".join(artistList)) elif self.mtype == "m4a": audio = MP4(self.path) return audio.tags['\xa9ART'][0]
def remove_metadata(self): if MUTAGEN: if "MP3" in self.__audio_codec: try: tags = ID3(self.__filepath) except ID3NoHeaderError: return tags.delete(self.__filepath, delete_v1=True, delete_v2=True) elif "ogg" in self.__gst_type: tags = OggVorbis(self.__filepath) tags.delete() elif "flac" in self.__gst_type: tags = FLAC(self.__filepath) tags.delete()
def download_flac(track: tidalapi.models.Track, file_path, album=None): if album is None: album = track.album url = session.get_media_url(track_id=track.id) r = requests.get(url, stream=True) r.raw.decode_content = True data = BytesIO() shutil.copyfileobj(r.raw, data) data.seek(0) audio = FLAC(data) # general metatags audio['artist'] = track.artist.name audio[ 'title'] = f'{track.name}{f" ({track.version})" if track.version else ""}' # album related metatags audio['albumartist'] = album.artist.name audio[ 'album'] = f'{album.name}{f" ({album.version})" if album.version else ""}' audio['date'] = str(album.year) # track/disc position metatags audio['discnumber'] = str(track.volumeNumber) audio['disctotal'] = str(album.numberOfVolumes) audio['tracknumber'] = str(track.trackNumber) audio['tracktotal'] = str(album.numberOfTracks) # Tidal sometimes returns null for track copyright if hasattr(track, 'copyright') and track.copyright: audio['copyright'] = track.copyright elif hasattr(album, 'copyright') and album.copyright: audio['copyright'] = album.copyright # identifiers for later use in own music libraries if hasattr(track, 'isrc') and track.isrc: audio['isrc'] = track.isrc if hasattr(album, 'upc') and album.upc: audio['upc'] = album.upc pic = Picture() pic.type = id3.PictureType.COVER_FRONT pic.width = 640 pic.height = 640 pic.mime = 'image/jpeg' r = requests.get(track.album.image, stream=True) r.raw.decode_content = True pic.data = r.raw.read() audio.add_picture(pic) data.seek(0) audio.save(data) with open(file_path, "wb") as f: data.seek(0) shutil.copyfileobj(data, f)
def flac(): song = FLAC(file) write_keys(song) if exists(cover_img): pic = Picture() pic.data = open(cover_img, 'rb').read() pic.mime = 'image/jpeg' song.add_picture(pic) song.save()
def sendAudio(chat_id, audio, link=None, image=None, youtube=False): sleep(0.8) try: bot.sendChatAction(chat_id, "upload_audio") if os.path.isfile(audio): audio = open(audio, "rb") try: tag = EasyID3(audio.name) duration = int(MP3(audio.name).info.length) except mutagen.id3._util.ID3NoHeaderError: tag = FLAC(audio.name) duration = int(tag.info.length) data = { "chat_id": "@deezer_spotify", # chat_id, "duration": duration, "performer": tag['artist'][0], "title": tag['title'][0] } file = { "audio": audio, "thumb": image } url = "https://api.telegram.org/bot" + token + "/sendAudio" try: request = requests.post(url, params=data, files=file, timeout=20) # response = bot.sendAudio(chat_id, audio) except: request = requests.post(url, params=data, files=file, timeout=20) # response = bot.sendAudio(chat_id, audio) if request.status_code != 200: # print(str(response)) sendMessage(chat_id, translate(language_dictionary[chat_id], strings.the_song + tag['artist'][0] + " - " + tag['title'][0] + strings.too_big)) print("too big") else: if youtube is False: file_id = request.json()['result']['audio']['file_id'] bot.sendAudio(chat_id, file_id, disable_notification=True) write_db("INSERT INTO DWSONGS(id, query, quality) values('%s', '%s', '%s')" % ( link, file_id, audio.name.split("(")[-1].split(")")[0])) pass else: bot.sendAudio(chat_id, audio, disable_notification=True) except telepot.exception.TelegramError: sendMessage(chat_id, translate(language_dictionary[chat_id], strings.track_not_in_deezer) + "({0})".format(link)) except Exception as e: print(e) sendMessage(chat_id, translate(language_dictionary[chat_id], strings.cant_find_track))
def file_extnxion(maddox, aud_dir): if aud_dir.endswith('.flac'): try: audio = FLAC(aud_dir) maddox.inflate(audio['artist'][0], audio['album'][0], audio['title'][0]) except: print('Mutagen Flac Error') else: try: audio = ID3(aud_dir) maddox.inflate(audio['TPE1'].text[0], audio['TALB'].text[0], audio['TIT2'].text[0]) except: print('Mutagen ID3 Error')
def parse(self): """Read the FLAC file and update the variables.""" try: self._flac = FLAC(self.path) info = self._flac.info self.streaminfo = StreamInfo( info.channels, info.bits_per_sample, info.sample_rate, info.total_samples ) if self._flac.cuesheet is not None: self.cuesheet = CueSheet(self._flac.cuesheet) else: self.cuesheet = None self.tags = Tags(self._flac.tags) self.parse_ok = True self.parse_exception = None except Exception as e: self.parse_ok = False self.parse_exception = e self.streaminfo = None self.cuesheet = None self.tags = None
def save(self): """ flac and mp3 support the same keys from mutagen, .m4a does not """ if self.year_found is False and self.style_found is False: return if self.suffix == '.flac': self._image_flac() audio = FLAC(self.path) if self.suffix == '.mp3': self._image_mp3() audio = EasyID3(self.path) if self.suffix == '.m4a': self._save_m4a() return if self.style_found: if cfg.overwrite_genre: audio['genre'] = self.genres self.genres_updated = True else: if self.local_genres == '': audio['genre'] = self.genres self.genres_updated = True if self.year_found: if cfg.overwrite_year: audio['date'] = self.year self.year_updated = True else: if self.local_year == '': audio['date'] = self.year self.year_updated = True audio.save()
def verify(files, trackids): path = config.TEMP_PATH if path[-1] != '/': path += '/' path += 'verify/' tmp_files = [] if trackids is None: if config.CONVERT_TO_WAV_BEFORE_VERIFY: for i in range(len(files)): fn = path + str(i) + '.wav' ffmpeg.convert(files[i], fn) tmp_files.append(fn) else: for i in range(len(files)): fn = path + str(i) + '.flac' copyfile(files[i], fn) tmp_files.append(fn) else: for i in range(len(files)): fn = path + str(i) + '.flac' copyfile(files[i], fn) audio = FLAC(fn) audio['TRACKNUMBER'] = str(trackids[i]) audio['TITLE'] = 'test_album' audio.save() if config.CONVERT_TO_WAV_BEFORE_VERIFY: fn2 = path + str(i) + '.wav' ffmpeg.convert(fn, fn2) tmp_files.append(fn2) os.remove(fn) else: tmp_files.append(fn) cmd = config.ARCUEDOTNET_COMMAND + [tmp_files[0]] p = Popen(cmd, stdout=PIPE, stderr=PIPE) so, er = p.communicate() return so.decode()
def extract_images(self, file_path, image_in, base_path): var = FLAC(file_path) pics = var.pictures images = [] types_added = [] for p in pics: if p.type not in types_added: print("found front cover") print(f'image type: {p.type}') image = self._extract_image(p, image_in) images.append(image) types_added.append(p.type) else: print(f'Type {p.type} found in list. Skipping') return images
def main(): logging.basicConfig(level=logging.DEBUG) parser = argparse.ArgumentParser( description='Converts wav files to flac files. ' 'The flac file is written next to the wav file. ' 'It assumes that the input wav file tags are written in SHIFT-JIS.') parser.add_argument('files', metavar='FILES', type=str, nargs='+', help='Audio files to be converted to flac.') args = parser.parse_args() args.files for f in args.files: track_info = _GetWavTrackInfo(f) flac_file = _ToFlac(f) if not track_info: continue flac = FLAC(flac_file) flac["title"] = track_info.name flac["album"] = track_info.product flac["date"] = track_info.year logging.info(flac) flac.save()
def test_write_changetitle_unicode_value(self): f = FLAC(self.NEW) if PY3: self.assertRaises(TypeError, f.__setitem__, b'title', u"A Unicode Title \u2022") else: f[b"title"] = u"A Unicode Title \u2022" f.save() f = FLAC(self.NEW) self.failUnlessEqual(f[b"title"][0], u"A Unicode Title \u2022")
def sendAudio( chat_id, audio, link = None, image = None, youtube = False ): sleep(default_time) try: if os.path.isfile(audio): bot.sendChatAction(chat_id, "upload_audio") try: tag = EasyID3(audio) duration = int(MP3(audio).info.length) except ID3NoHeaderError: tag = FLAC(audio) duration = int(tag.info.length) if os.path.getsize(audio) < telegram_audio_api_limit: file_id = bot.sendAudio( chat_id, open(audio, "rb"), caption= '🎵@MusicIsrael🎧', thumb = open(image.url, "rb"), duration = duration, performer = 'ראשונים במוזיקה', title = tag['artist'][0]+" - "+tag['title'][0] )['audio']['file_id'] if not youtube: quality = fast_split(audio) link = "track/%s" % link.split("/")[-1] write_db( insert_query % ( link, file_id, quality ) ) else: sendMessage(chat_id, "השיר גדול מדי :(") else: bot.sendAudio(chat_id, audio) except error.BadRequest: sendMessage(chat_id, "השיר: %s לא נמצא בדיזר :(" % link)
def retag(filename): audio = FLAC(filename) audio.delete() artist, title = os.path.splitext(filename)[0].split(' - ', 1) audio['artist'] = artist audio['title'] = title audio.save(deleteid3=True) print(' Cleared metadata.\n Tagged flac with:') print(' artist: %r' % artist) print(' title: %r' % title)
def audioFile(audio): aud_str = str(audio) if aud_str.endswith(".mp3"): aud1 = MP3(audio) len1 = aud1.info.length return int(len1) elif aud_str.endswith('.wav'): aud2 = WAVE(audio) len2 = aud2.info.length return int(len2) elif aud_str.endswith('.flac'): aud3 = FLAC(audio) len3 = aud3.info.length return int(len3) elif aud_str.endswith('.aac'): aud4 = AAC(audio) len4 = aud4.info.length return int(len4) elif aud_str.endswith('.ac3'): aud5 = AC3(audio) len5 = aud5.info.length return int(len5) elif aud_str.endswith('.aiff'): aud6 = AIFF(audio) len6 = aud6.info.length return int(len6) elif aud_str.endswith('.asf'): aud7 = ASF(audio) len7 = aud7.info.length return int(len7) elif aud_str.endswith('.dsf'): aud8 = DSF(audio) len8 = aud8.info.length return int(len8) elif aud_str.endswith('.mp4'): aud9 = MP4(audio) len9 = aud9.info.length return int(len9) elif aud_str.endswith('.smf'): aud10 = SMF(audio) len10 = aud10.info.length return int(len10) elif aud_str.endswith('.ogg'): aud12 = OggFileType(audio) len12 = aud12.info.length return int(len12) else: return str("File type not supported.")
def main(): # set up for logging LEVELS = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL, } if len(sys.argv) > 1: level_name = sys.argv[1] level = LEVELS.get(level_name, logging.NOTSET) logging.basicConfig( format='%(asctime)s - %(levelname)-8s - %(message)s\n', level=level, datefmt='%Y-%m-%d %H:%M:%S') logger = logging.getLogger(__name__) logger.debug('Entering main') oversized_covers = 0 # pic_not_found = True for root, dirs, files in os.walk('/home/robertm'): # print(f'root: {root}') for file in files: if file.lower().endswith('.flac'): f = os.path.join(root, file) p = FLAC(f) pics = p.pictures if not pics: print(f'no pic found: {f}') # print(f'type(pics) == {type(pics)}') # print(f'{pics}') for i in pics: size = sys.getsizeof(i.data) if size > 150000: print(f'{size:10,} --> {f}') oversized_covers += 1 # if i.type == 3: # front cover # print(f'found front cover - {i.desc}') # print(f'sizeof data == {sys.getsizeof(i.data)}') # with open("cover.jpg", "wb") as f: # f.write(i.data) flac = FLACFile(f) print(f'ttl files processed: {FLACFile.ttl_files_processed}') print(f'ttl file size: {FLACFile.ttl_file_size:,}') print(f'ttl over sized covers: {oversized_covers}')
def test_write_changetitle(self): f = FLAC(self.NEW) if PY3: self.assertRaises(TypeError, f.__setitem__, b'title', b"A New Title") else: f[b"title"] = b"A New Title" f.save() f = FLAC(self.NEW) self.failUnlessEqual(f[b"title"][0], b"A New Title")
def _generate_image_from_flac(self, flacPath): # if we don't have the python module to # extract image from flac, we just return # default file's icon try: from mutagen.flac import FLAC except ImportError: return FILE_ICON try: audio = FLAC(flacPath) art = audio.pictures return self._generate_image_from_art(art, flacPath) except IndexError, TypeError: return FILE_ICON