def artwork(path1, path2): if not (os.path.exists(path1) and os.path.exists(path2)): return f1 = music_tag.load_file(path1) f2 = music_tag.load_file(path2) try: f2["artwork"] except KeyError: f2["artwork"] = f1["artwork"] f2.save()
def download_song(playlist_t, name, artist): cname = name cartist = artist illegal = ['NUL','\'', '\"', '\\', '//', ':', '*', '"', '<', '>', '|', '/', '?'] for i in illegal: cname = cname.replace(i, '_') cartist = cartist.replace(i, '_') filename = "{} - {}.mp3".format(cartist, cname) directory = "./download/{}/".format(playlist_t) try: if not filename in str(listdir(directory)): results = YoutubeSearch("{} by {} lyrics".format(name, artist), max_results=1).to_json() ydl_opts = { 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], 'outtmpl': 'download/' + playlist_t + '/current.%(etx)s', 'quiet': False } print("Downloading: {}".format(filename)) with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download(['https://www.youtube.com/watch?v={}'.format(json.loads(results)["videos"][0]["id"])]) print("Renaming file to {}".format(filename)) os.rename( "{}current.mp3".format(directory), "{}{}".format(directory, filename) ) print("Setting tags") f = music_tag.load_file(directory + filename) f["title"] = name f["artist"] = artist f.save() else: print("{} already exists".format(filename)) except Exception as e: print(e) # if input("Try again? (yes / no) ") == "no": # sys.exit() print("[Error] Trying again in 5") sleep(1) print("[Error] Trying again in 4") sleep(1) print("[Error] Trying again in 3") sleep(1) print("[Error] Trying again in 2") sleep(1) print("[Error] Trying again in 1") sleep(1) print("[Error] Trying again") download_song(playlist_title, name, artist)
def get_details(path): audiofile = music_tag.load_file(path) title = audiofile['title'] artist = audiofile['artist'] if str(artist) == "": artist = str(audiofile['albumartist']) + " [Album Artist]" return title, artist
def file_info_view(): request_body = request.get_json(force=True) if "path" in request_body: path = request_body["path"] else: raise Exception("you must specify a path") path = re.sub(r'^/', '', path) path = re.sub(r'\.\./', '', path) path = os.path.join(settings["media_dir"], path) if not os.path.exists(path): raise Exception("requested path does not exist") if not os.path.isfile(path): raise Exception("requested path is not a file") file = music_tag.load_file(path) # gettings tags tags = {} for tag_name in settings["file_tags"]: tags[tag_name] = file[tag_name].value response = { "tags": tags, } # getting artwork (if any) artwork = file['artwork'] if artwork.first is not None: artwork_b64 = "data:" + artwork.first.mime + ";base64," + b64encode( artwork.first.data).decode('ascii') response["artwork"] = artwork_b64 return response
def check_dir(self, path): items = os.listdir(path) downloaded_tracks = [] song = "" artist = "" for file_name in items: file_path = os.path.join(path, file_name) try: mp3 = music_tag.load_file(file_path) song = mp3['title'].value artist = mp3['artist'].value except HeaderNotFoundError: print("[ERR] MP3 Corrupted!") self.debug.append("[ERR] MP3 Corrupted!") except NotImplementedError as e: print("[ERR] Not Impltemented Error for: ") self.debug.append("[ERR] Not Impltemented Error for: ") print(file_path) self.debug.append(file_path) self.debug.append("[ERR] Error: {0}".format(e)) downloaded_tracks.append(artist + " - " + song) return downloaded_tracks
def retag_mp3(name, path): argv = name.split(" - ") n = len(argv) tag = music_tag.load_file(path) #tag.clear() # title # artist - title # artist - album - title # artist - album - cur_track|max_track - title # artist - album - cur_track - max_track - title if(n == 1): tag["title"] = argv[0] elif(n == 2): tag["artist"] = argv[0] tag["title"] = argv[1] elif(n == 3): tag["artist"] = argv[0] tag["album"] = argv[1] tag["title"] = argv[2] elif(n == 4): tag["artist"] = argv[0] tag["album"] = argv[1] trackNum = argv[2].split("|") tag["tracknumber"] = trackNum[0] tag["totaltracks"] = trackNum[1] tag["title"] = argv[3] else: print("\033[5;41m[E]\033[0m\033[31m Mp3 name have {}(n) \" - \" !!!\033[0m".format(n)) tag.save()
def load_track(self, file_path) -> None: ''' Loads an audio file. --- Raises: NotImplementedError ''' self._current_file = load_file(file_path)
async def add_metadata( file: Path, thumbnail: Optional[Path] = None, album: Optional[str] = None, artist: Optional[str] = None, composer: Optional[str] = None, comment: Optional[str] = None, genre: Optional[str] = None, year: Optional[int] = None, title: Optional[str] = None, ): music = music_tag.load_file(str(file.absolute())) tags = { "album": album, "title": title, "albumartist": artist, "composer": composer, "comment": comment, "genre": genre, "year": year, "tracktitle": title, } for name, value in tags.items(): if value is not None: music[name] = value if thumbnail: with thumbnail.open("rb") as opened_image: music["artwork"] = opened_image.read() music.save()
def add_start_time_single(key, album): cur_time = 0 for file in album: f = music_tag.load_file(file) rounded_time = round(cur_time) h = rounded_time // 3600 m = rounded_time % 3600 // 60 s = rounded_time % 3600 % 60 if h == 0: tag_value = '{:d}:{:02d}'.format(m, s) else: tag_value = '{:d}:{:02d}:{:02d}'.format(h, m, s) f.set_raw(tag_name, tag_name, tag_value, appendable=False) f.save() print('Added start time tag {} to {} in Album {}'.format(tag_value, f['tracktitle'], key)) try: length = int(re.search("'length': \['(\d+)'\]", str(f.mfile)).group(1)) except: try: # try using TinyTag from tinytag import TinyTag tag = TinyTag.get(file) length = tag.duration except: # skip remaining album return cur_time = cur_time + length
def save_tags_to_file(file: str, tags: dict, new_art_path: str) -> str: """Create an return an instance of `tag_editor_keyboard` **Keyword arguments:** - file (str) -- The path of the file - tags (str) -- The dictionary containing the tags and their values - new_art_path (str) -- The new album art to set **Returns:** The path of the file """ music = music_tag.load_file(file) try: if new_art_path: with open(new_art_path, 'rb') as art: music['artwork'] = art.read() except OSError as error: raise Exception("Couldn't set hashtags") from error music['artist'] = tags['artist'] if tags['artist'] else '' music['title'] = tags['title'] if tags['title'] else '' music['album'] = tags['album'] if tags['album'] else '' music['genre'] = tags['genre'] if tags['genre'] else '' music['year'] = int(tags['year']) if tags['year'] else 0 music['disknumber'] = int(tags['disknumber']) if tags['disknumber'] else 0 music['tracknumber'] = int(tags['tracknumber']) if tags['tracknumber'] else 0 music.save() return file
def set_metadata(file, infos): song = music_tag.load_file(file) song['title'] = infos[0] song['artist'] = infos[1] with open(os.path.join("Artworks", "temp_art.jpg"), 'rb') as artwork: song['artwork'] = artwork.read() song.save()
def openaudio(filepath): # Create MP3File instance. audio = music_tag.load_file(filepath) # Get/set/del tags value. title = audio["title"].value.rstrip('\x00') artist = audio["artist"].value.rstrip('\x00') audio2 = mutagen.File(filepath) length = floor(audio2.info.length) return (title, artist, length)
def check_file_tag(data_track, song_id): global audiofile audiofile = music_tag.load_file(data_track['fpath']) comment_tag = str(audiofile['comment']).split('\n') if len(comment_tag) > 2: song_id_file = get_last_segment(comment_tag[1]) if song_id_file == song_id: return True return False return True
def main(): mode = 0 if len(sys.argv) != 2: print("path to FLAC files missing") exit(1) else: flacdir = sys.argv[1] current_album = "" current_artist = "" # walk through directory given as ARGV and all subdirs currentDirectory = os.getcwd() for (subdir, dirs, files) in os.walk(flacdir): for filename in files: filepath = subdir + os.sep + filename if filepath.endswith(".flac"): tag = music_tag.load_file(filepath) # Do we have a new album to process? if (str(tag['albumartist']) != current_artist) or (str( tag['album']) != current_album): current_album = str(tag['album']) current_artist = str(tag['albumartist']) # get FLAC metadata audio = FLAC(filepath) # Look in the comments for either ##nodiscogs## (leave me alone) or ###<title>### (special title to assign) discogs_comments_raw = str(audio.vc) comment_pos = discogs_comments_raw.find('COMMENT') if comment_pos: discogs_comments_raw = discogs_comments_raw[ comment_pos:10000] comment_pos = discogs_comments_raw.find('\')') discogs_comments_raw = discogs_comments_raw[ 11:comment_pos] # no Discogs release available? Skip album. if "##nodiscogs##" in discogs_comments_raw: message = "[Skipped, no Discogs release] - " print(message + current_artist + " - " + current_album) break # does it have a Discogs release assigned we can use for tagging? if not ("DISCOGS_RELEASE_ID" in audio): # No Discogs release assigned: ask to run the tagge if query_yes_no( current_artist + " - " + current_album + ": No Discogs release assigned. Start Tagger?" ): directory = os.path.join(currentDirectory, subdir) return_code = subprocess.call(tagger + " \"" + directory + "\"", shell=True)
def actualizar(self): self.getMeta() for i in self.asps: f = music_tag.load_file(i) self.songs.insert_at_start([ str(f['title']), str(f['artist']), str(f['genre']), str(f['year']), i ]) for x in range(len(self.trees)): self.trees[x].insert(self.songs.start_node, x) self.asps.clear()
def bcwav(directory): for _filename in os.listdir(directory): if _filename.endswith("wav"): file = music_tag.load_file(f'{directory}{_filename}') filename = _filename.split(' - ') file['artist'] = filename[0] file['album'] = filename[1] file['tracknumber'] = filename[-1][0:2] file['discnumber'] = filename[-1][0:2] file['tracktitle'] = filename[-1][3:-4] file.save() track_name = filename[-1][3:] os.rename(f'{directory}{_filename}', f'{directory}{track_name}')
def get_all_albums(files): albums = {} for file in files: f = music_tag.load_file(file) key = '' for key_elem in album_keys: key = key + str(f[key_elem]) if key not in albums: albums[key] = [file] else: albums[key].append(file) return albums
def get_meta(folder, album_dest, file): song = os.path.join(f'{folder}/{file}') meta = music_tag.load_file(song) try: image_data = meta['artwork'].first.data filename = file.split('.')[0] + '.jpg' with open(f'{album_dest}/{filename}', 'wb') as f: f.write(image_data) artwork = filename except Exception as e: artwork = "" return {'album': meta['album'].value, 'artist': meta['artist'].value, 'title': meta['tracktitle'].value, 'filename': file, 'artwork': artwork}
def load(self, exit_on_exc=True, debug=False): try: if self.is_json: self.tags = read_json(self.full_path()) else: self.tags = music_tag.load_file(self.full_path()) return self.tags except Exception as e: error('Couldn\'t load', self.full_path, fatal=exit_on_exc, exc=e, debug=debug) return None
def main_id3(path): audiofile = music_tag.load_file(path) comment = audiofile['comment'] com = str(comment) genres = ID3Editor.after(com, "- ") comment_split_by_space = com.split(" ") key = comment_split_by_space[0] energy = comment_split_by_space[2] """THIS IS MAY BE CAUSING PROBLEMS WORK ON IN FUTURE""" comment_split_by_comma = genres.split(", ") categories = [] for item in comment_split_by_comma: categories.append(item) return categories, key, energy
def update_metadata(self, song_data): """Updates the metadata of the stored MP3 (if it exists) to fit the information stored in the database. :author: Carlos :param song_data: The information about the song stored in the database. :PRE: _ :POST: The song metadata will be updated if it exists. """ song_path = self.get_song_path(song_data["song_id"]) if song_path: f = music_tag.load_file(song_path) f['artist'] = song_data["group_name"] f['genre'] = song_data["genre"] f['tracktitle'] = song_data["song_name"] f.save()
def get_song_artwork_base64(path): if not path: return None path = re.sub(r'^/', '', path) path = re.sub(r'\.\./', '', path) path = os.path.join(settings["media_dir"], path) if not os.path.exists(path): return None if not os.path.isfile(path): return None file = music_tag.load_file(path) artwork = file['artwork'] if artwork.first is not None: return "data:" + artwork.first.mime + ";base64," + b64encode( artwork.first.data).decode('ascii') else: return None
def create(): file = request.files['file'] file.save(secure_filename(file.filename)) cwd = os.getcwd() files = os.listdir(cwd) try: f = music_tag.load_file(files[0]) except Exception as e: return 'File not supported', os.remove(files[0]) statement = 'Action is Successful: 200 OK' if str(f['#codec']) == 'mp3': if str(request.form['option']) == 'song': new_file = Song(name_of_song=str(f['tracktitle']), duration=int(f['#length'])) db.session.add(new_file) db.session.commit() return render_template('index.html', statement=statement), os.remove(files[0]) elif str(request.form['option']) == 'podcast': new_file = Podcast(name_of_podcast=str(f['tracktitle']), duration=int(f['#length']), host=str(f['album'])) db.session.add(new_file) db.session.commit() return render_template('index.html', statement=statement), os.remove(files[0]) elif str(request.form['option']) == 'audiobook': new_file = Audiobook(title_audiobook=str(f['tracktitle']), author_title=str(f['composer']), narrator=str(f['artist']), duration=int(f['#length'])) db.session.add(new_file) db.session.commit() return render_template('index.html', statement=statement), os.remove(files[0]) else: return 'The request is invalid: 400 bad request', os.remove(files[0]) return 'Internal Server Error', os.remove(files[0])
def set_metadata(self, song_path, song): try: mp3 = music_tag.load_file(song_path) mp3['title'] = song['name'] mp3['artist'] = song['artist'] mp3['genre'] = song['genre'] mp3['year'] = song['year'] mp3['album'] = song['album'] del mp3['tracknumber'] mp3.save() except HeaderNotFoundError as err: print("[ERR] Corrupted MP3!! deleting...:" + song['artist'] + " - " + song['name']) self.debug.append("[ERR] Corrupted MP3!! deleting...:" + song['artist'] + " - " + song['name']) self.debug.append("[ERR] Error: {0}".format(err)) os.remove(song_path)
def check_track_numbers_and_sort(key, album): track_numbers = {} for file in album: f = music_tag.load_file(file) track_num = int(f['track_number'].value) if track_num in track_numbers: print('Invalid Album - repeated Tracknumber - Albumkey: ' + key) return False, None else: track_numbers[track_num] = file track_numbers = OrderedDict(sorted(track_numbers.items(), key=lambda t: t[0])) if list(track_numbers.keys())[0] != 1 or list(track_numbers.keys())[-1] != len(track_numbers): print('Invalid Album - Tracknumbers missing - Albumkey: ' + key) return False, None return True, track_numbers.values()
def clean(filepath, config): # "only clean music metadata" ok_extension = False for ext in config.valid_extensions: ok_extension |= filepath.endswith(ext) if not ok_extension: return audio = music_tag.load_file(filepath) title = audio["title"].value artist = audio["artist"].value # only consider first tag if there is many audio["title"] = cleanstr(title, config) audio["artist"] = cleanstr(artist, config) audio.save() # if mp3, fix length issue: no quality is lost by re-encode but # bitrate and length will be fixed if re.match(r'.*\.mp3', str(filepath)): fix_duration(filepath)
def set_tag(session, data_track, additional_data_track=None): global audiofile if not audiofile: audiofile = music_tag.load_file(data_track['fpath']) audiofile['album'] = data_track['malbum'] audiofile['albumartist'] = data_track['msinger'] audiofile['tracktitle'] = data_track['msong'] audiofile['comment'] = 'Generated By jaris58 \n' + \ get_single_link(data_track['encodeSongId']) + '\n' + \ str(url_str) if get_mode(str(url_str)) == 'album': audiofile['tracknumber'] = data_track['tracknumber'] if additional_data_track: audiofile['artist'] = ", ".join([i['name'] for i in additional_data_track['artist_list']]) audiofile['genre'] = additional_data_track['genre'] if 'genre' in additional_data_track else None audiofile['year'] = str(additional_data_track['release_time']) \ if 'release_time' in additional_data_track else None if additional_data_track['lrc_exist'] == 1: audiofile['lyrics'] = str(base64.b64decode(additional_data_track['lrc_content'])) \ if 'lrc_content' in additional_data_track else None else: audiofile['lyrics'] = None else: audiofile['artist'] = data_track['msinger'] audiofile['genre'] = None audiofile['year'] = None audiofile['lyrics'] = None if data_track['imgSrc'] != "": response_img = session.get(data_track['imgSrc']) audiofile['artwork'] = response_img.content try: audiofile.save() audiofile = None except Exception: audiofile = None print("Skipped " + get_info(data_track) + " in use.")
def upload_audio(request): context = {} if request.method == 'POST': upload_audio_form = UploadAudioForm(request.POST, request.FILES) if upload_audio_form.is_valid(): audio_file = request.FILES['audio_file'] fs = FileSystemStorage() file_name = fs.save(audio_file.name, audio_file) # Edit metadata f = music_tag.load_file(fs.location + '/' + audio_file.name) f['title'] = upload_audio_form.cleaned_data['title'] f['artist'] = upload_audio_form.cleaned_data['artist'] f['album'] = upload_audio_form.cleaned_data['album'] f.save() with open(fs.location + '/' + audio_file.name, 'rb') as updated_file: response = HttpResponse(updated_file.read(), content_type='audio/mp4a-latm') response['Content-Disposition'] = 'inline; filename=' + upload_audio_form.cleaned_data['title'] + '.m4a' return response else: upload_audio_form = UploadAudioForm() context['form'] = upload_audio_form return render(request, 'audio_properties/upload_audio.html', context=context)
def download_audio(self, vid, qual, target_dir, ind, n): if qual == "Highest": path = vid.streams.get_audio_only( subtype="webm").download(target_dir) for stream in vid.streams: if stream.mime_type == "audio/webm" and stream.abr == qual: path = stream.download(target_dir) break else: path = vid.streams.get_audio_only( subtype="webm").download(target_dir) new_path = path[:-5] + ".mp3" file = AudioFileClip(path) self.message_label.setText( f"Converting audio stream to mp3.. ({ind + 1} of {n})") file.write_audiofile(new_path) file.close() os.remove(path) metadata = vid.metadata.metadata f = music_tag.load_file(new_path) f['artist'] = (metadata[0]['Artist'] if len(metadata) > 0 and metadata[0].get('Artist') is not None else vid.author) f['comment'] = vid.description f['compilation'] = False f['composer'] = f['artist'] f['tracktitle'] = (metadata[0]['Song'] if len(metadata) > 0 and metadata[0].get('Song') is not None else vid.title) f['year'] = vid.publish_date.year f.save() return new_path
def handle_music_message(update: Update, context: CallbackContext) -> None: message = update.message user_id = update.effective_user.id user_data = context.user_data music_duration = message.audio.duration music_file_size = message.audio.file_size old_music_path = user_data['music_path'] old_art_path = user_data['art_path'] old_new_art_path = user_data['new_art_path'] language = user_data['language'] if music_duration >= 3600 and music_file_size > 48000000: message.reply_text( translate_key_to(lp.ERR_TOO_LARGE_FILE, language), reply_markup=generate_start_over_keyboard(language) ) return context.bot.send_chat_action( chat_id=message.chat_id, action=ChatAction.TYPING ) try: create_user_directory(user_id) except OSError: message.reply_text(translate_key_to(lp.ERR_CREATING_USER_FOLDER, language)) logger.error("Couldn't create directory for user %s", user_id, exc_info=True) return try: file_download_path = download_file( user_id=user_id, file_to_download=message.audio, file_type='audio', context=context ) except ValueError: message.reply_text( translate_key_to(lp.ERR_ON_DOWNLOAD_AUDIO_MESSAGE, language), reply_markup=generate_start_over_keyboard(language) ) logger.error("Error on downloading %s's file. File type: Audio", user_id, exc_info=True) return try: music = music_tag.load_file(file_download_path) except (OSError, NotImplementedError): message.reply_text( translate_key_to(lp.ERR_ON_READING_TAGS, language), reply_markup=generate_start_over_keyboard(language) ) logger.error( "Error on reading the tags %s's file. File path: %s", user_id, file_download_path, exc_info=True ) return reset_user_data_context(context) user_data['music_path'] = file_download_path user_data['art_path'] = '' user_data['music_message_id'] = message.message_id user_data['music_duration'] = message.audio.duration tag_editor_context = user_data['tag_editor'] artist = music['artist'] title = music['title'] album = music['album'] genre = music['genre'] art = music['artwork'] year = music.raw['year'] disknumber = music.raw['disknumber'] tracknumber = music.raw['tracknumber'] if art: art_path = user_data['art_path'] = f"{file_download_path}.jpg" with open(art_path, 'wb') as art_file: art_file.write(art.first.data) tag_editor_context['artist'] = str(artist) tag_editor_context['title'] = str(title) tag_editor_context['album'] = str(album) tag_editor_context['genre'] = str(genre) tag_editor_context['year'] = str(year) tag_editor_context['disknumber'] = str(disknumber) tag_editor_context['tracknumber'] = str(tracknumber) show_module_selector(update, context) increment_usage_counter_for_user(user_id=user_id) user = User.where('user_id', '=', user_id).first() user.username = update.effective_user.username user.push() delete_file(old_music_path) delete_file(old_art_path) delete_file(old_new_art_path)