def addID3(self, title, title2, artist): print("Tagging "+"{0}.mp3".format(title)) try: t = stagger.read_tag("{0}.mp3".format(title)) except: # Try to add an empty ID3 header. # As long stagger crashes when there's no header, use this hack. # ID3v2 infos : http://id3.org/id3v2-00 m = open("{0}.mp3".format(title), 'r+b') old = m.read() m.seek(0) m.write(b"\x49\x44\x33\x02\x00\x00\x00\x00\x00\x00" + old) # Meh... m.close # Let's try again... try: t = stagger.read_tag("{0}.mp3".format(title)) # Slicing is to get the whole track name # because SoundCloud titles usually have # a dash between the artist and some name split = title2.find("-") if not split == -1: t.title = title2[(split + 2):] t.artist = title2[:split] else: t.title = title2 t.artist = artist t.write() except: print("[Warning] Can't add tags, skipped.")
def create(self): self.file = self.parentApp.current_file try: self.meta = stagger.read_tag(self.file) except stagger.errors.NoTagError: temp = stagger.Tag23() # create a id3v2.3 tag instance temp.album = ' ' # so that there is something to write to the file temp.write(self.parentApp.current_file) self.meta = stagger.read_tag(self.parentApp.current_file) self.meta.album = '' # revert what was just done self.meta.write() self.tit = self.add(npy.TitleText, name='Title', value=self.meta.title) self.nextrely += 1 self.alb = self.add(npy.TitleText, name='Album', value=self.meta.album) self.nextrely += 1 self.art = self.add(npy.TitleText, name='Artist', value=self.meta.artist) self.nextrely += 1 self.ala = self.add(npy.TitleText, name='Album Artist', value=self.meta.album_artist) self.nextrely += 2 self.gen = self.add(npy.TitleText, name='Genre', value=self.resolve_genre(self.meta.genre)) self.nextrely += 1 self.tno = self.add( npy.TitleText, name='Track Number', value=str(self.meta.track if self.meta.track != 0 else ''))
def testID3v2ExtendedHeader(self): # First sample simply includes an empty extended header. tag1 = stagger.read_tag( os.path.join(sample_dir, "23.synthetic.empty-extended-header.lossy.id3")) self.assertEqual(tag1.title, "The Millionaire's Holiday") self.assertEqual(tag1.album, "Best Of Combustible Edison") self.assertEqual(tag1.date, "1997") self.assertEqual(tag1.track, 1) self.assertEqual(tag1.genre, "Foobar") self.assertEqual(tag1.artist, "Combustible Edison") self.assertEqual(tag1.comment, " 0000132D 0000132D 00002FF0") self.assertEqual(tag1.flags, {"extended_header"}) # Second sample file has an (invalid) CRC32 number in its extended # header. tag2 = stagger.read_tag( os.path.join(sample_dir, "23.synthetic.extended-header-bad-crc.lossy.id3")) self.assertEqual(tag2.title, "The Millionaire's Holiday") self.assertEqual(tag2.album, "Best Of Combustible Edison") self.assertEqual(tag2.date, "1997") self.assertEqual(tag2.track, 1) self.assertEqual(tag2.genre, "Foobar") self.assertEqual(tag2.artist, "Combustible Edison") self.assertEqual(tag2.comment, " 0000132D 0000132D 00002FF0") self.assertEqual(tag2.flags, {"ext:crc_present", "extended_header"}) self.assertEqual(tag2.crc32, 0x20202020)
def testID3v2ExtendedHeader(self): # First sample simply includes an empty extended header. tag1 = stagger.read_tag(os.path.join(sample_dir, "23.synthetic.empty-extended-header.lossy.id3")) self.assertEqual(tag1.title, "The Millionaire's Holiday") self.assertEqual(tag1.album, "Best Of Combustible Edison") self.assertEqual(tag1.date, "1997") self.assertEqual(tag1.track, 1) self.assertEqual(tag1.genre, "Foobar") self.assertEqual(tag1.artist, "Combustible Edison") self.assertEqual(tag1.comment, " 0000132D 0000132D 00002FF0") self.assertEqual(tag1.flags, { "extended_header" }) # Second sample file has an (invalid) CRC32 number in its extended header. tag2 = stagger.read_tag(os.path.join(sample_dir, "23.synthetic.extended-header-bad-crc.lossy.id3")) self.assertEqual(tag2.title, "The Millionaire's Holiday") self.assertEqual(tag2.album, "Best Of Combustible Edison") self.assertEqual(tag2.date, "1997") self.assertEqual(tag2.track, 1) self.assertEqual(tag2.genre, "Foobar") self.assertEqual(tag2.artist, "Combustible Edison") self.assertEqual(tag2.comment, " 0000132D 0000132D 00002FF0") self.assertEqual(tag2.flags, { "ext:crc_present", "extended_header" }) self.assertEqual(tag2.crc32, 0x20202020)
def addID3(self, title, title2, artist): print("Tagging " + "{0}.mp3".format(title)) try: t = stagger.read_tag("{0}.mp3".format(title)) except: # Try to add an empty ID3 header. # As long stagger crashes when there's no header, use this hack. # ID3v2 infos : http://id3.org/id3v2-00 m = open("{0}.mp3".format(title), 'r+b') old = m.read() m.seek(0) m.write(b"\x49\x44\x33\x02\x00\x00\x00\x00\x00\x00" + old) # Meh... m.close # Let's try again... try: t = stagger.read_tag("{0}.mp3".format(title)) # Slicing is to get the whole track name # because SoundCloud titles usually have # a dash between the artist and some name split = title2.find("-") if not split == -1: t.title = title2[(split + 2):] t.artist = title2[:split] else: t.title = title2 t.artist = artist t.write() except: print("[Warning] Can't add tags, skipped.")
def get_ID3_tags(self, album, file_path): try: album.artist = stagger.read_tag(file_path).artist album.title = stagger.read_tag(file_path).album if not album.artist or not album.title: return None return True except stagger.errors.NoTagError: return None
def test_write_id3(self): """ Test write id3 tags """ sandbox = os.path.dirname(os.path.realpath(__file__)) + "/sandbox/" sample = os.path.dirname(os.path.realpath(__file__)) + "/samples/" filename = "92583301-dem-beats-3.mp3" if not os.path.exists(sandbox): os.mkdir(sandbox) shutil.copyfile(sample + filename, sandbox + filename) tag = stag() tag._process_artwork_tmpfile = Mock(return_value=False) client = Mock() track = strack(json_obj[0], client=client) tag.load_id3(track) tag.write_id3(sandbox + filename) res = stagger.read_tag(sandbox + filename) self.assertEqual("Some text", res[TIT1].text[0]) self.assertEqual("Foo", res[TIT2].text[0]) self.assertEqual("dubstep bass", res[TIT3].text[0]) self.assertEqual("247010", res[TLEN].text[0]) self.assertEqual("foo", res[TOFN].text[0]) self.assertEqual("Dubstep", res[TCON].text[0]) self.assertEqual("free", res[TCOP].text[0]) self.assertEqual("1387373820", res[TDOR].text[0]) self.assertEqual("https://foobar.dev/1337", res[WOAS].url) self.assertEqual("https://api.foobar.dev/1337", res[WOAF].url) self.assertEqual("user1", res[TPUB].text[0]) self.assertEqual("http://user1.dev", res[WOAR][0].url) self.assertEqual("User 1", res[TPE1].text[0]) self.assertEqual("User 1 Soundcloud tracks", res[TALB].text[0]) shutil.rmtree(sandbox)
def add_location(location): entry = {} entry['location'] = location entry['encoding'] = encoding.from_file(location.encode('utf-8')).decode('utf-8') entry['mime'] = mime.from_file(location.encode('utf-8')).decode('utf-8') if os.path.isdir(location): entry['type'] = 'folder' elif os.path.isfile(location): entry['type'] = 'file' (root, ext) = os.path.splitext(location) if ext: entry['extension'] = ext[1:] if ext[1:].lower() == 'mp3': print(location) tag = stagger.read_tag(location) for t in tag.values(): print(t) print(tag.title) print(tag.comment) ''' try: tag = stagger.read_tag(location) for t in tag.values(): print(t) print(t.comment) except: # No tag:w pass ''' sys.exit()
def get(self, track_id): self.set_header("Content-Type", "application/json") filepath = library[int(track_id)]["filepath"] tag = stagger.read_tag(filepath) ret_obj = {} ret_obj["artist"] = tag.artist # if 'APIC' in tag._frames: # apic_frame = tag._frames['APIC'] # ret_obj["albumart"] = [] # for art in apic_frame: # m = hashlib.md5() # m.update(art.data) # hashdata = m.digest() # hash = base64.b16encode(hashdata).decode("ASCII") # if not hash in image_dict: # image_dict[hash] = { # "mimetype": art.mime, # "data": art.data # } # ret_obj["albumart"].append(hash) self.write(json.dumps(ret_obj))
def play_file(path): song_data = stagger.read_tag(path) json_export = { 'title': song_data.title, 'artist': song_data.artist, 'album': song_data.album, } if json_export['album'] == '': json_export['album'] = 'single' f = open('temp/song.json', 'w') json.dump(json_export, f) f.close() try: by_data = song_data[stagger.id3.APIC][0].data im = io.BytesIO(by_data) image_file = Image.open(im) image_file.save('static/cover.png') except: shutil.copyfile('static/default_cover.png', 'static/cover.png') mixer.music.load(path) mixer.music.play() wait_for_end()
def show_song_details(self): self.song_length = self.my_player.get_song_length(self.song_name) min, sec = divmod(self.song_length, 60) min = round(min) sec = round(sec) if (sec <= 9): self.songTotalDuration.configure(text=str(min) + ":0" + str(sec)) else: self.songTotalDuration.configure(text=str(min) + ":" + str(sec)) ext_index = self.song_name.rfind(".") song_name_str = self.song_name[0:ext_index] if (len(song_name_str) > 14): song_name_str = song_name_str[0:14] + "..." self.songName.configure(text=song_name_str) try: self.song_path = self.my_player.get_song_path(self.song_name) self.mp3 = stagger.read_tag(self.song_path) self.by_data = self.mp3[stagger.id3.APIC][0].data self.im = io.BytesIO(self.by_data) self.imageFile = Image.open(self.im) self.new_imageFile = self.imageFile.resize((200, 200)) self.photo = ImageTk.PhotoImage(self.new_imageFile) self.label.configure(image=self.photo) except KeyError: self.label.configure(image=self._img20)
def setAlbum(files): global PATH_MUSIC fname = 'count.txt' length = len(files) open_dialog('Setting album names') try: with open(fname, 'r') as f: count = int(f.read()) except: count = 0 for i in range(length): changeProgress(i + 1, length, files[i]) count += 1 mp3 = read_tag(f'{PATH_MUSIC}/{files[i]}') mp3.album = str(count) mp3.write() root.destroy() try: with open(fname, 'w') as f: f.write(str(count)) except: error = 'Failed to write count.txt\nGive write permissions' messagebox.showinfo('Error', error, icon="warning")
def scan_path(session, not_found, path): url = urlunparse(('file', '', path, '', '', '')) if url in not_found: del not_found[url] return LOG.debug('Scanning {0}.'.format(path)) try: tag = read_tag(path) if not (tag and tag.artist and tag.title): LOG.warn('No ID3 for {0}.'.format(path)) return try: artist = session.query(LocalArtist).filter( LocalArtist.name == tag.artist).one() except NoResultFound: artist = LocalArtist(name=tag.artist) session.add(artist) track = LocalTrack(url=url, name=tag.title, local_artist=artist) session.add(track) session.commit() except UnicodeEncodeError as e: LOG.warn('Cannot encode ID3 for {0} ({1}).'.format(path, e)) session.rollback() except NoTagError as e: LOG.warn('Cannot read ID3 for {0} ({1}).'.format(path, e)) except ValueError as e: LOG.warn('Cannot read ID3 for {0} ({1}).'.format(path, e))
def play(): path = request.args["path"] try: mp3 = stagger.read_tag(path) data = mp3[stagger.id3.APIC][0].data song = EasyID3(path) except stagger.errors.NoTagError: song = FLAC(path) data = song.pictures[0].data i_encoded = "data:image/jpeg;base64, %s" % b64encode(data).decode() title = song["title"][0] artist = song["artist"][0] album = song["album"][0] path = download_api % path return render_template( "player.html", title=title, artist=artist, album=album, image=i_encoded, path=path, )
def testIssue37(self): # Check that duplicate frames are handled OK. # The sample file contains two TALB frames ("quux" and "Foo"). # This is invalid according to the spec. tag = stagger.read_tag( os.path.join(sample_dir, "24.issue37.stagger.duplicate-talb.id3")) # The friendly API should just concatenate the frames, as if they were # a single multivalued text frame. self.assertEqual(tag.album, "quux / Foo") # Ditto for the magical dictionary API. self.assertEqual(tag[TALB], TALB(encoding=0, text=["quux", "Foo"])) # However, both getframes() and frames() should show two separate # frames. self.assertEqual( tag.frames(TALB), [TALB(encoding=0, text="quux"), TALB(encoding=0, text="Foo")]) self.assertEqual(tag.frames(orig_order=True), [ TIT2(encoding=0, text="Foobar"), TALB(encoding=0, text="quux"), TALB(encoding=0, text="Foo") ])
def add_tracks(track, layer, log): global track_count record = [str(track_count), track, ''] track_count += 1 try: mp3_tag = stagger.read_tag(track) for tag in mp3_tag_list[3:-2]: record.append(str(getattr(mp3_tag, tag))) comment_col = 13 record[comment_col] = record[comment_col].replace('\n', '').replace('\r', '') if len(record[comment_col]) > 99: record[comment_col] = record[comment_col][:99] record.append('') # action placeholder record.append(getcwd().strip()) try: log.writerow(commas_out(record)) except: pass except stagger.errors.NoTagError: #print(indentation*(layer+1), track, 'Tag cannot be read') for count in range(11): record.append('') record.append('Tag cannot be read;') record.append(getcwd().strip()) log.writerow(commas_out(record))
def copySongs(source,target): windows = True win = "\\" lin = "/" os.chdir(source) a = [ name for name in os.listdir(os.getcwd()) if os.path.isdir(os.path.join(os.getcwd(), name)) ] for x in a: os.chdir(source) os.chdir(x) b = [ name for name in os.listdir(os.getcwd()) if os.path.isfile(os.path.join(os.getcwd(), name)) ] for y in b: os.chdir(source) os.chdir(x) oldfilename = os.getcwd()+"\\"+y try: tag = stagger.read_tag(y) title = removeSymbols(tag.title.strip()) artist = removeSymbols(tag.artist.strip()) trackNr = tag.track album = removeSymbols(tag.album.strip()) filename = str(trackNr)+" - "+title+".mp3" except: title = y artist = "NO ID3 TAG" trackNr = random.randint(0, 20) album = "NoAlbum" filename = str(trackNr)+" - "+title if len(album) > 0: if windows: fullpath = target+win+artist+win+album+win else: fullpath = target+lin+artist+lin+album+lin else: if windows: fullpath = target+win+artist+win+"NoAlbum"+win else: fullpath = target+lin+artist+lin+"NoAlbum"+lin fullfilepath = fullpath+filename if os.path.exists(r''+fullfilepath+''): pass else: if windows: if os.path.exists(r''+target+win+artist): os.chdir(r''+target+win+artist) else: os.mkdir(r''+target+win+artist) os.chdir(r''+target+win+artist) else: if os.path.exists(r''+target+lin+artist): os.chdir(r''+target+lin+artist) else: os.mkdir(r''+target+lin+artist) os.chdir(r''+target+lin+artist) if os.path.exists(r''+fullpath): os.chdir(r''+fullpath) else: os.mkdir(r''+fullpath) os.chdir(r''+fullpath) print(fullfilepath) shutil.copyfile(r''+oldfilename+'', r''+fullfilepath+'')
def db_insert_file(filename, file): """Reads file metadata and inserts it into the database.""" id3_file = None try: id3_file = read_tag(path.join(app.config["UPLOAD_FOLDER"], filename)) except NoTagError: # No ID3 tags whatsoever print("Inserting misc file: " + filename) query = "INSERT IGNORE INTO ytfs_meta (filename) VALUES ('{0}');".format(filename) cursor.execute(query) db.commit() return track = id3_file.track if id3_file.track is not None else 0 title = id3_file.title.replace("'", "\\'") artist = id3_file.artist.replace("'", "\\'") album = id3_file.album.replace("'", "\\'") year = id3_file.date.replace("'", "\\'") genre = id3_file.genre.replace("'", "\\'") track_comment = id3_file.comment.replace("'", "\\'") print("Inserting: " + artist + " - " + title) query = "INSERT IGNORE INTO ytfs_meta (filename, track, title, artist, album, year, genre, track_comment) " + \ "VALUES ('{0}', {1}, '{2}', '{3}', '{4}', '{5}', '{6}', '{7}');".format( \ filename, track, title, artist, album, year, genre, track_comment ) cursor.execute(query) db.commit() # Save changes back to DB
def cmd_cloud_audio(message): bot.reply_to(message, "<b>Audio Received</b>", parse_mode='HTML') bot.send_chat_action(message.chat.id, 'upload_audio') # bot.forward_message(config.ADMIN, message.chat.id, message.message_id) fileID = message.audio.file_id file_info = bot.get_file(fileID) downloaded_file = bot.download_file(file_info.file_path) filename = message.audio.title + " - " + message.audio.performer + ".mp3" file = os.path.join(config.PATH['audio'], filename) with open(file, 'wb') as new_file: new_file.write(downloaded_file) mp3 = stagger.read_tag(downloaded_file) mp3.title = message.audio.title mp3.artist = message.audio.performer mp3.picture = message.audio.thumb.file_id mp3.write(file) print(file) bot.reply_to( message, "<b>Status:</b>Audio Saved\n<b>Name:</b>{0}\n<b>Location:</b>{1}". format(filename, config.PATH), parse_mode='HTML')
def scan_path(session, not_found, path): url = urlunparse(('file', '', path, '', '', '')) if url in not_found: del not_found[url] return LOG.debug('Scanning {0}.'.format(path)) try: tag = read_tag(path) if not (tag and tag.artist and tag.title): LOG.warn('No ID3 for {0}.'.format(path)) return try: artist = session.query(LocalArtist).filter(LocalArtist.name == tag.artist).one() except NoResultFound: artist = LocalArtist(name=tag.artist) session.add(artist) track = LocalTrack(url=url, name=tag.title, local_artist=artist) session.add(track) session.commit() except UnicodeEncodeError as e: LOG.warn('Cannot encode ID3 for {0} ({1}).'.format(path, e)) session.rollback() except NoTagError as e: LOG.warn('Cannot read ID3 for {0} ({1}).'.format(path, e)) except ValueError as e: LOG.warn('Cannot read ID3 for {0} ({1}).'.format(path, e))
def load_id3(self, path): data = {} keys = [ 'album', 'album_artist', 'artist', 'composer', 'genre', 'sort_album', 'sort_album_artist', 'sort_artist', 'sort_composer', 'sort_title', 'title', 'track_total', 'date' ] multikeys = { 'album': 'albums', 'album_artist': 'artists', 'artist': 'artists', 'composer': 'composers', 'genre': 'genres', 'sort_album': 'albums', 'sort_album_artist': 'artists', 'sort_artist': 'artists', 'sort_composer': 'composers' } tag = stagger.read_tag(path) for key in keys: if not hasattr(tag, key): continue obj = getattr(tag, key) if isinstance(obj, Number) or \ (isinstance(obj, str) and \ len(obj) > 0): data[key] = obj if key in multikeys: mkey = multikeys[key] if mkey not in data: data[mkey] = [] if obj not in data[mkey]: data[mkey].append(obj) return data
def music_getter(self): files_getter = QFileDialog.getOpenFileNames() for address in files_getter: if file[len(file) - 4:] == '.mp3' or file[len(file) - 4:] == '.wav': self.AddressList.append(address) tags = read_tag(address) self.NameList.append(tags.title) if tags.genre != '': if tags.genre in self.genres.keys(): self.genres[tags.genre].append(file) else: self.genres[tags.genre] = [] self.genres[tags.genre].append(file) else: self.genres['unknown'].append(file) if tags.artist != '': if tags.artist in self.artists: self.artists[tags.artist].append(file) else: self.artists[tags.artist] = [] self.artists[tags.artist].append(file) else: self.artists['unknown'].append(file) if tags.album != '': if tags.album in self.albums: self.albums[tags.album].append(file) else: self.albums[tags.album] = [] self.albums[tags.album].append(file) else: self.albums['unknown'].append(file) else: pass
def copyMusic(targetPath, sourcePath): for root, dir, files in os.walk(sourcePath): for file in files: try: tag = stagger.read_tag(os.path.join(root, file)) album = tag.album.replace('/','').replace('\\', '').replace('?','').replace('*','')\ .replace(':','').replace('"','').replace('>','').replace('<','').replace('|','').strip() artist = tag.artist.replace('/','').replace('\\', '').replace('?','').replace('*','')\ .replace(':','').replace('"','').replace('>','').replace('<','').replace('|','').strip() songPath = os.path.join(targetPath, artist, album) if not os.path.exists(songPath): os.makedirs(songPath) filename, extension = os.path.splitext(os.path.join( root, file)) if tag.track: newFileName = str( tag.track) + ' - ' + tag.title + extension else: newFileName = tag.title + extension newFileName = newFileName.replace('/','').replace('\\', '').replace('?','').replace('*','')\ .replace(':','').replace('"','').replace('>','').replace('<','').replace('|','').strip() os.rename(os.path.join(root, file), os.path.join(root, newFileName)) shutil.copy(os.path.join(root, newFileName), os.path.join(songPath, newFileName)) os.rename(os.path.join(root, newFileName), os.path.join(root, file)) except: pass
def add_song(): global folder for file in files: moved_file=shutil.move(file,folder) realdir=os.path.realpath(moved_file) audio=stagger.read_tag(realdir) audio1=MP3(realdir) length=int(audio1.info.length) minute=int(length/60) sec=int(length%60) conn=sqlite3.connect("Music_book.db") c=conn.cursor() c.execute("INSERT INTO metadata VALUES (NULL,:s_location,:s_title,:s_album,:s_year,:s_genre,:s_artist,:s_minutes,:s_seconds)", { "s_location":realdir, "s_title":audio.title, "s_album":audio.album, "s_year":audio.date, "s_genre":audio.genre, "s_artist":audio.artist, "s_minutes":minute, "s_seconds":sec }) conn.commit() conn.close() select_entry.delete(0,END)
def writeTag(file, songartist, song, show): "write tag info. for some reason this won't work as root" tag = stagger.read_tag(file) tag.title = song tag.artist = songartist tag.album = show tag.write()
def load_id3(path): data = {} keys = ['album', 'album_artist', 'artist', 'composer', 'genre', 'sort_album', 'sort_album_artist', 'sort_artist', 'sort_composer', 'sort_title', 'title', 'track_total', 'date' ] multikeys = { 'album': 'albums', 'album_artist': 'artists', 'artist': 'artists', 'composer': 'composers', 'genre': 'genres', 'sort_album': 'albums', 'sort_album_artist': 'artists', 'sort_artist': 'artists', 'sort_composer': 'composers' } tag = stagger.read_tag(path) for key in keys: if not hasattr(tag, key): continue obj = getattr(tag, key) if isinstance(obj, Number) or \ (isinstance(obj, str) and \ len(obj) > 0): data[key] = obj if key in multikeys: mkey = multikeys[key] if mkey not in data: data[mkey] = [] if obj not in data[mkey]: data[mkey].append(obj) return data
async def audio_upload(message: Message, path, del_path: bool = False, extra: str = ""): title = None artist = None thumb = None duration = 0 strpath = str(path) file_size = humanbytes(os.stat(strpath).st_size) try: album_art = stagger.read_tag(strpath) if album_art.picture and not os.path.lexists(Config.THUMB_PATH): bytes_pic_data = album_art[stagger.id3.APIC][0].data bytes_io = io.BytesIO(bytes_pic_data) image_file = Image.open(bytes_io) image_file.save("album_cover.jpg", "JPEG") thumb = "album_cover.jpg" except stagger.errors.NoTagError: pass if not thumb: thumb = await get_thumb(strpath) metadata = extractMetadata(createParser(strpath)) if metadata and metadata.has("title"): title = metadata.get("title") if metadata and metadata.has("artist"): artist = metadata.get("artist") if metadata and metadata.has("duration"): duration = metadata.get("duration").seconds sent: Message = await message.client.send_message( message.chat.id, f"`Uploading {path.name} as audio ... {extra}`") start_t = datetime.now() await message.client.send_chat_action(message.chat.id, "upload_audio") try: msg = await message.client.send_audio( chat_id=message.chat.id, audio=strpath, thumb=thumb, caption=f"{path.name} [ {file_size} ]", title=title, performer=artist, duration=duration, parse_mode="html", disable_notification=True, progress=progress, progress_args=(message, f"uploading {extra}", str(path.name)), ) except ValueError as e_e: await sent.edit(f"Skipping `{path}` due to {e_e}") except Exception as u_e: await sent.edit(u_e) raise u_e else: await sent.delete() await finalize(message, msg, start_t) finally: if os.path.lexists("album_cover.jpg"): os.remove("album_cover.jpg") if os.path.exists(str(path)) and del_path: os.remove(str(path))
def process_file(self, f): track = stagger.read_tag(f) self._titles.append(Title(track.title, track.artist, 1,#track[TLEN].text[0], f, int(track[TBPM].text[0]), track[TKEY].text[0], track.genre))
def write_track_info(self, track, track_file): tag = stagger.read_tag(track_file) tag.title = track.title tag.artist = track.artist tag.album = track.album tag.album_artist = track.album_artist tag.track = track.track_number tag.write()
def get_cover(self): try: audio_tag = stagger.read_tag(self.path) byte_im = audio_tag[stagger.id3.PIC][0].data im = io.BytesIO(byte_im).getvalue() return im except KeyError: return None
def embed_image(self, path, string): print("Embedding image...") tag = stagger.read_tag(path) tt = tag[stagger.id3.APIC][0] tt.data = string tag.write() print("Done")
def play(self): if self.music_file: mixer.init() mixer.music.load(MusicPlayer.filename) mixer.music.play() mp3 = stagger.read_tag(MusicPlayer.filename) self.label['text'] = os.path.basename(MusicPlayer.filename)
def sortFile(name, root, dirs): sFile = NewFile(name) sFile.root = root sFile.path = os.path.join(root, name) if sFile.root != fromLocation: sFile.baselevel = False # set the type of file if sFile.name.endswith(videoFileExt): sFile.type = "video" elif sFile.name.endswith(musicFileExt): sFile.type = "music" elif sFile.name.endswith(imageFileExt): sFile.type = "image" else: sFile.type = "NA" if sFile.type == "video": # only care about season info if its a video for list in fileSeason: regex = re.compile(list) list2 = regex.findall(name) for l in list2: if l != "": sFile.l1 = l sFile.hasseason = True if len(sFile.l1) == 6: sFile.seasonnum = int(sFile.l1[1:3]) if len(sFile.l1) == 4: sFile.seasonnum = int(sFile.l1[1:2]) if sFile.type == "video": if sFile.hasseason == True: # shows # find Show Folder tmpPath = findFolder("folder", sFile.name, showFolder.path, str(sFile.seasonnum)) if sFile.seasonnum != 0: # find season Folder tmpPath = findFolder("season", str(sFile.seasonnum), tmpPath, str(sFile.seasonnum)) sFile.moveto = tmpPath else: # Movies sFile.moveto = movieFolder.path elif sFile.type == "image": sFile.moveto = picFolder.path elif sFile.type == "music": tmpPath = "" audiofile = stagger.read_tag(sFile.path) tmpPath = findFolder("folder", audiofile.artist, musicFolder.path, "") tmpPath = findFolder("folder", audiofile.album, tmpPath, "") sFile.moveto = tmpPath if sFile.moveto != "": writeReport( sFile.path + " was moved to " + sFile.moveto + "\\" + sFile.name + "\n") if not os.path.exists(sFile.moveto + "\\" + sFile.name): shutil.copy(sFile.path, sFile.moveto + "\\" + sFile.name) with printLock: print(sFile.name)
def setArt(song, art): global PATH_IMAGES, PATH_ERRORS try: mp3 = read_tag(song) mp3.picture = art mp3.write() except: with open(f'{PATH_ERRORS}/errors(setArt).txt', 'a+') as f: f.write(f'{song} not found in {PATH_IMAGES}\n')
def tagPath(mp3s): """Return a path built from the tags of the given mp3 files.""" tagPaths = [] for mp3 in mp3s: tag = stagger.read_tag(mp3) tagPaths.append(os.path.join(tag.artist, tag.album, " ".join(["{0:02d}".format(tag.track), tag.title]) )) return tagPaths
def setArt(songPath, image): global PATH_ERRORS try: mp3 = read_tag(songPath) mp3.picture = image mp3.write() except: with open(f'{PATH_ERRORS}/errors(setArt).txt', 'a+') as f: f.write(f'Error setting image of {songPath}\n')
def tag(self, music_file: DownloadedMusicFile): tags = self.__parse_tags(music_file) audio_tags = stagger.read_tag(music_file.file_mp3) audio_tags.album = tags.album audio_tags.artist = tags.artist audio_tags.title = tags.title audio_tags.picture = tags.file_thumbnail audio_tags.write()
def next_song(): global sid, ignition, playround, dbfile, aux, title, album, artist if (aux == 1): return () if (ignition == 2): filename = get_next_offline_song() else: check_playround() # Check if playround ends db = sqlite3.connect(dbfile) # Load database cursor = db.cursor() cursor.execute("SELECT sid,filename FROM `songs` \ LEFT JOIN (SELECT * FROM disabled_songs WHERE mode=" + str(mode) + ") AS d USING(sid) \ WHERE mode is null \ AND playround < " + str(playround) + " \ ORDER BY listened,skipped,RANDOM() \ LIMIT 1;") try: song = cursor.fetchone() sid = song[0] except TypeError: print("Error while fetching song from DB") skip_song() return () cursor.execute("UPDATE songs SET playround=" + str(playround) + " WHERE sid=" + str(sid) + ";") db.commit() filename = song[1] cursor.close() db.close() # Close DB print("Song: " + filename + "(SID:" + str(sid) + ")") if not os.path.isfile(filename): print("File not found!") skip_song() pygame.mixer.music.set_volume(1) try: pygame.mixer.music.load(filename) except: print("Unable to play " + filename) time.sleep(0.1) return () pygame.mixer.music.play() try: id3 = stagger.read_tag(filename) title = id3.title album = id3.album artist = id3.artist except: title = os.path.basename(filename) artist = "" album = "" print("title: " + title) print("album: " + album) print("artist: " + artist) print("playing:" + filename) update_display()
def GetSongInfo(filename): try: tag = stagger.read_tag(filename) except: return None else: ret = "" + tag.title + "\n" ret += "*" + tag.artist + "*\n" ret += "*" + tag.album + "*" return ret
def scan(basepath, logfunc): file_matcher = re.compile(r".*\.(mp3)") image_dict = {} tracks = [] i = 0 for dirpath, dirnames, filenames in os.walk(basepath): for filename in filenames: if file_matcher.match(filename): filepath = os.path.join(dirpath, filename) try: tag = stagger.read_tag(filepath) albumart = {} if 'APIC' in tag._frames: apic_frame = tag._frames['APIC'] for art in apic_frame: m = hashlib.md5() m.update(art.data) hashdata = m.digest() hash = base64.b16encode(hashdata).decode("ASCII") if not hash in image_dict: image_dict[hash] = { "mimetype": art.mime, "data": art.data } albumart[art.type] = hash tracks.append({ "index": i, "title": tag.title, "track": tag.track, "artist": tag.artist, "album": tag.album, "disc": tag.disc if tag.disc > 0 else 1, "album_artist": tag.album_artist if tag.album_artist != "" else tag.artist, "date": tag.date, "filepath": filepath, "album_art": albumart }) i = i + 1 if i % 100 == 0: logfunc("{0} tracks".format(i)) except stagger.errors.NoTagError as err: logfunc("No tag found in {0}".format(filepath)) logfunc("Scan complete - {0} tracks found".format(i)) return (tracks, image_dict)
def testFrameOrder(self): # 24.stagger.sample-01.id3 contains a simple test tag that has file frames # in the following order: # # TIT2("TIT2"), TPE1("TPE1"), TALB("TALB"), TRCK("TRCK"), TPE2("TPE2") testfile = os.path.join(os.path.dirname(__file__), "samples", "24.stagger.sample-01.id3") framelist = [TRCK, TPE2, TALB, TIT2, TPE1] # Read tag, verify frame ordering is preserved tag = stagger.read_tag(testfile) self.assertEqual(len(tag), 5) self.assertEqual(set(tag.keys()), set(frame.frameid for frame in framelist)) self.assertEqual( [frame.frameid for frame in tag.frames(orig_order=True)], [frame.frameid for frame in framelist]) # Test frame contents for framecls in framelist: # tag[TIT2] == tag["TIT2"] self.assertTrue(framecls in tag) self.assertTrue(framecls.frameid in tag) self.assertEqual(tag[framecls], tag[framecls.frameid]) # type(tag[TIT2]) == TIT2 self.assertTrue(isinstance(tag[framecls], framecls)) # Each frame contains a single string, which is the frame id in # lowercase. self.assertEqual(len(tag[framecls].text), 1) self.assertEqual(tag[framecls].text[0], framecls.frameid.lower()) # Encode tag with default frame ordering, verify result is different. with open(testfile, "rb") as file: filedata = file.read() tag.padding_max = 0 # Default sorting order is different. tagdata = tag.encode() self.assertEqual(len(tagdata), len(filedata)) self.assertFalse(tagdata == filedata) # Override the sort order with an empty list, # verify resulting order is the same as in the original file. tag.frame_order = stagger.tags.FrameOrder() tagdata = tag.encode() self.assertTrue(tagdata == filedata) tag2 = stagger.decode_tag(tagdata) self.assertTrue(tag == tag2)
def testFrameOrder(self): # 24.stagger.sample-01.id3 contains a simple test tag that has file frames # in the following order: # # TIT2("TIT2"), TPE1("TPE1"), TALB("TALB"), TRCK("TRCK"), TPE2("TPE2") testfile = os.path.join(os.path.dirname(__file__), "samples", "24.stagger.sample-01.id3") framelist = [TRCK, TPE2, TALB, TIT2, TPE1] # Read tag, verify frame ordering is preserved tag = stagger.read_tag(testfile) self.assertEqual(len(tag), 5) self.assertEqual( set(tag.keys()), set(frame.frameid for frame in framelist)) self.assertEqual([frame.frameid for frame in tag.frames(orig_order=True)], [frame.frameid for frame in framelist]) # Test frame contents for framecls in framelist: # tag[TIT2] == tag["TIT2"] self.assertTrue(framecls in tag) self.assertTrue(framecls.frameid in tag) self.assertEqual(tag[framecls], tag[framecls.frameid]) # type(tag[TIT2]) == TIT2 self.assertTrue(isinstance(tag[framecls], framecls)) # Each frame contains a single string, which is the frame id in # lowercase. self.assertEqual(len(tag[framecls].text), 1) self.assertEqual(tag[framecls].text[0], framecls.frameid.lower()) # Encode tag with default frame ordering, verify result is different. with open(testfile, "rb") as file: filedata = file.read() tag.padding_max = 0 # Default sorting order is different. tagdata = tag.encode() self.assertEqual(len(tagdata), len(filedata)) self.assertFalse(tagdata == filedata) # Override the sort order with an empty list, # verify resulting order is the same as in the original file. tag.frame_order = stagger.tags.FrameOrder() tagdata = tag.encode() self.assertTrue(tagdata == filedata) tag2 = stagger.decode_tag(tagdata) self.assertTrue(tag == tag2)
def main(args=sys.argv[1:]): fpath = args[0] # stagger.read_tag関数でmp3ファイルタグから情報を読み込む tag = stagger.read_tag(fpath) print(tag) print(tag.title) print(tag.album)
def next_song(): global sid,ignition,playround,dbfile,aux,title,album,artist if(aux==1): return() if(ignition == 2): filename=get_next_offline_song() else: check_playround() # Check if playround ends db = sqlite3.connect(dbfile) # Load database cursor=db.cursor() cursor.execute("SELECT sid,filename FROM `songs` \ LEFT JOIN (SELECT * FROM disabled_songs WHERE mode="+str(mode)+") AS d USING(sid) \ WHERE mode is null \ AND playround < "+str(playround)+" \ ORDER BY listened,skipped,RANDOM() \ LIMIT 1;") try: song=cursor.fetchone() sid=song[0] except TypeError: print("Error while fetching song from DB") skip_song() return() cursor.execute("UPDATE songs SET playround="+str(playround)+" WHERE sid="+str(sid)+";") db.commit() filename=song[1] cursor.close(); db.close() # Close DB print("Song: "+filename+"(SID:"+str(sid)+")") if not os.path.isfile(filename): print("File not found!") skip_song() pygame.mixer.music.set_volume(1) try: pygame.mixer.music.load(filename) except: print("Unable to play "+filename) time.sleep(0.1) return() pygame.mixer.music.play() try: id3=stagger.read_tag(filename) title=id3.title album=id3.album artist=id3.artist except: title=os.path.basename(filename) artist="" album="" print("title: "+title) print("album: "+album) print("artist: "+artist) print("playing:"+filename) update_display()
def __init__(self, d_song): try: if d_song == None: self._ok = False return self._album = stagger.read_tag(d_song).album self._artist = stagger.read_tag(d_song).artist self._date = stagger.read_tag(d_song).date self._file = d_song self._genre = stagger.read_tag(d_song).genre self._title = stagger.read_tag(d_song).title self._track = stagger.read_tag(d_song).track self._ttrack = stagger.read_tag(d_song).track_total self._disc = stagger.read_tag(d_song).disc self._tdisc = stagger.read_tag(d_song).disc_total self._comment = stagger.read_tag(d_song).comment self._aart = '' # self._aart = lastfm.getAlbumArt( self._artist, self._title ) self._ok = True except IOError: raise SongError('File does not exist')
def id3_to_track (filepath): sFktname = "id3_to_track" tag = stagger.read_tag(filepath) track_new = track() track_new["artist"] = tag.artist track_new["title"] = tag.title track_new["tn"] = tag.track return track_new
def __init__( self, d_song ): try: if d_song == None: self._ok = False return self._album = stagger.read_tag( d_song ).album self._artist = stagger.read_tag( d_song ).artist self._date = stagger.read_tag( d_song ).date self._file = d_song self._genre = stagger.read_tag( d_song ).genre self._title = stagger.read_tag( d_song ).title self._track = stagger.read_tag( d_song ).track self._ttrack = stagger.read_tag( d_song ).track_total self._disc = stagger.read_tag( d_song ).disc self._tdisc = stagger.read_tag( d_song ).disc_total self._comment = stagger.read_tag( d_song ).comment self._aart = '' # self._aart = lastfm.getAlbumArt( self._artist, self._title ) self._ok = True except IOError: raise SongError( 'File does not exist' )
def testEmptyStrings(self): # 24.stagger.empty-strings.id3 consists of a TIT2 frame with 13 extra # NUL characters at the end. testfile = os.path.join(os.path.dirname(__file__), "samples", "24.stagger.empty-strings.id3") with warnings.catch_warnings(record=True) as ws: tag = stagger.read_tag(testfile) self.assertEqual(tag[TIT2].text, ["Foobar"]) self.assertEqual(len(ws), 1) self.assertEqual(ws[0].category, stagger.FrameWarning) self.assertEqual(ws[0].message.args, ("TIT2: Stripped 13 empty strings " "from end of frame",))
def change_picture(self, song): mp3 = stagger.read_tag(song) by_data = mp3[stagger.id3.APIC][0].data im = io.BytesIO(by_data) # set size picture in app imageFile = Image.open(im).resize((300, 300), Image.ANTIALIAS) photo = ImageTk.PhotoImage(imageFile) # change picture when music next and previous self.ImageLabel.configure(image=photo) self.ImageLabel.image = photo
def run(self): for filename in self.files: self.filename = os.path.realpath(filename) if self.filename.split(".")[-1] == "mp3" and self.checked: try: tag = stagger.read_tag(self.filename) old_tag = tag.album self.kopiert.emit( "--Ändere mp3 ID3 von \"{}\" auf \"Podcast\"\n".format(old_tag)) tag.album = "Podcast" tag.write() if tag.title: self.new_filename = "" for i in self.filename.split("/")[:-1]: self.new_filename += i + "/" self.new_filename += tag.title + ".mp3" os.rename(self.filename, self.new_filename) self.kopiert.emit("Kopiere: {}\n".format( self.new_filename.split("/")[-1])) shutil.copy(self.new_filename, self.dropbox) else: self.kopiert.emit("Kopiere: {}\n".format( self.filename.split("/")[-1])) shutil.copy(self.filename, self.dropbox) except Exception as err: self.kopiert.emit("---Error bei {}: {}\n".format( self.filename.split("/")[-1], err)) try: self.kopiert.emit("Kopiere: {}\n".format( self.filename.split("/")[-1])) shutil.copy(self.filename, self.dropbox) except Exception as err2: self.kopiert.emit("---Error bei {}: {}\n".format( self.filename.split("/")[-1], err2)) else: self.kopiert.emit("Kopiere: {}\n".format( self.filename.split("/")[-1])) shutil.copy(self.filename, self.dst) if self.files: self.kopiert.emit("{}\n".format("*" * 80)) self.kopiert.emit("Kopieren fertig\n") self.kopiert.emit("{}\n".format("*" * 80)) else: self.kopiert.emit("{}\n".format("*" * 80)) self.kopiert.emit("Nichts zu kopieren\n") self.kopiert.emit("{}\n".format("*" * 80))
def tag_mp3(self, mp3file, tags, artpath): pass tag = stagger.read_tag(mp3file) tag.artist = tags["ARTIST"] tag.album = tags["ALBUM"] tag.title = tags["TITLE"] tag.track = tags["TRACKNUMBER"] tag.track_total = tags["TRACKTOTAL"] tag.disc = tags["DISCNUMBER"] tag.disc_total = tags["DISCTOTAL"] tag.date = tags["DATE"] tag.picture = artpath tag.write()
def testEmptyStrings(self): # 24.stagger.empty-strings.id3 consists of a TIT2 frame with 13 extra # NUL characters at the end. testfile = os.path.join(os.path.dirname(__file__), "samples", "24.stagger.empty-strings.id3") with warnings.catch_warnings(record=True) as ws: tag = stagger.read_tag(testfile) self.assertEqual(tag[TIT2].text, ["Foobar"]) self.assertEqual(len(ws), 1) self.assertEqual(ws[0].category, stagger.FrameWarning) self.assertEqual(ws[0].message.args, ("TIT2: Stripped 13 empty strings " "from end of frame", ))
def main(args=sys.argv[1:]): fpath = args[0] # stagger.read_tag 関数で mp3 ファイルからタグ情報を読み込む tag = stagger.read_tag(fpath) print(tag) #=>e<Tag23: ID3v2.3 tag with 11 frames> など # ID3 タグに記録されたタイトルを取得 print(tag.title) # ID3 タグに記録されたアルバム名を取得 print(tag.album)
def main(args=sys.argv[1:]): fpath = args[0] tag = stagger.read_tag(fpath) # タイトルを変更する tag.title = 'motto☆派手にね!' # アーティストを変更する tag.title = '戸松遥' # 同じファイルにタグ情報を書き出す tag.write()
def id3_picture(dir): LOG = getLogger('id3_picture') try: for file in listdir(dir): if file.endswith('.mp3'): LOG.debug('trying %s' % file) tag = read_tag(safejoin(dir, file)) for key in 'PIC', 'APIC': if key in tag: LOG.info('found %s' % file) pic = tag[key][0] yield pic.mime, pic.data except KeyboardInterrupt: raise except Exception as e: LOG.error(e)
def remove_frames(filename, frameids, act=True, verbose=False): try: tag = stagger.read_tag(filename) except stagger.NoTagError: verb(verbose, "{0}: no ID3 tag".format(filename)) return for frameid in frameids: try: del tag[frameid] verb(verbose, "{0}: {1}: deleted".format(filename, frameid)) except KeyError: verb(verbose, "{0}: {1}: not in file".format(filename, frameid)) if act: tag.write(filename)
def updateFile(filename): tag = stagger.read_tag(filename) artist = deblank(tag.artist) title = deblank(tag.title) lines = getLyrics(artist, title) # Create a lyrics object if len(lines) > 1: l = stagger.id3.USLT() l.encoding = 0 l.lang = "eng" l.text = lines tag[USLT]=[l] tag.write() print("Lyrics updated!") else: print("Lyrics cannot be found")