def analyze(self): with open(self.moodpath, "rb") as inputFile: cpt = 0 #read mood file while True: byte = inputFile.read(3) if len(byte) == 3: #calculate histogram self._countsR[int(ord(byte[0]) / 23)] += 1 self._countsG[int(ord(byte[1]) / 23)] += 1 self._countsB[int(ord(byte[2]) / 23)] += 1 #calculate enery self.energy_1 += pow(ord(byte[0]), 2) self.energy_2 += pow(ord(byte[1]), 2) self.energy_3 += pow(ord(byte[2]), 2) cpt += 1 else: break if cpt != 0: #end of enery calculation self.energy_1 /= cpt self.energy_2 /= cpt self.energy_3 /= cpt try: #fetch bitrate tag = TinyTag.get(self.filepath) if tag.bitrate < 512: br = int(round(tag.bitrate)) else: br = int(round(tag.bitrate/1000)) self.kbps = br except OSError as ose: print("Error: " + str(ose)) return (1) #get peak histogram self.peak_hist_1 = self.getCountsMax(self._countsR); self.peak_hist_2 = self.getCountsMax(self._countsG); self.peak_hist_3 = self.getCountsMax(self._countsB); return (0)
def sendAlbum(username): lsAlbums = [] lsDataTracks = [] lsTracks = [] numAlbum = 0 numTrack = 0 # Con este for buscaremos en la carpeta raiz luego las subcarpetas y archivos # Es for hace la funcion de buscar las canciones for root, dirs, files, in os.walk("musica\\cliente2\\Albums2"): for dirName in dirs: lsAlbums.append(dirName) numAlbum += 1 for root, dirs, files, in os.walk("musica\\cliente2\\Albums2\\" + dirName): for trackName in files: if trackName.endswith((".mp3", ".mp4a", ".flac", ".alac", ".wav", ".wma", ".ogg")): try: temp_track = TinyTag.get(root + "\\" + trackName) d = str(temp_track.duration) durationMinute = round(float(d), 0) duration = str(datetime.timedelta(seconds=durationMinute)) lsDataTracks = [trackName, temp_track.title, temp_track.artist, dirName, duration, temp_track.filesize, username] lsTracks.append(lsDataTracks) numTrack += 1 except TinyTagException: print("Error. No se puede leer el archivo.") return lsAlbums, numAlbum, lsTracks, numTrack
def sendAlbumClient(): lsAlbums = [] lsDataTracks = [] lsTracks = [] # Con este for buscaremos en la carpeta raiz luego las subcarpetas y archivos # Es for hace la funcion de buscar las canciones for root, dirs, files, in os.walk("musica\\cliente2\\Albums2"): for dirName in dirs: lsAlbums.append(dirName) for root, dirs, files, in os.walk("musica\\cliente2\\Albums2\\" + dirName): for trackName in files: if trackName.endswith((".mp3", ".mp4a", ".flac", ".alac", ".wav", ".wma", ".ogg")): try: temp_track = TinyTag.get(root + "\\" + trackName) try: file = open("musica\\cliente2\\Albums2\\" + dirName + "\\" + trackName, "rb") file_data = file.read() except: print("Error al leer archivo") file.close() lsDataTracks = [trackName, temp_track.title, temp_track.artist, file_data, dirName] lsTracks.append(lsDataTracks) except TinyTagException: print("Error. No se puede leer el archivo.") # print("\nLISTA DE CANCIONES: ", lsTracks) return lsTracks, lsAlbums # sendTrackClient() # sendAlbumClient()
def org(): for track in tracks: file = abs_path + '\\' + track try: temp = TinyTag.get(file) except: print("No files found in main dir.") break if temp.genre == "" or temp.genre == None or temp.genre == "Other": Path.mkdir(Path(abs_path + '\\Misc'), exist_ok=True) Path(file).replace(abs_path + '\Misc\\' + track) print("Misc folder has been updated.") continue if temp.genre in genres: Path(file).replace(abs_path + '\\' + temp.genre + '\\' + track) continue if temp.genre.find('/'): new = temp.genre.replace('/', '&') Path.mkdir(Path(abs_path + '\\' + new), exist_ok=True) Path(file).replace(abs_path + '\\' + new + '\\' + track) continue else: Path.mkdir(Path(abs_path + '\\' + temp.genre), exist_ok=True) Path(file).replace(abs_path + '\\' + temp.genre + '\\' + track)
def add_to_playlist(playlist, file): t = Tune() t.tune_content = file t.artist = 'temp999' t.album = 'temp999' t.title = 'temp999' t.owner = playlist.owner # must save at this point to get the absolute path so we can scan for meta tags t.save() try: tag = TinyTag.get(t.tune_content.path) t.artist = tag.artist t.title = tag.title t.album = tag.album except TinyTagException: # TODO: add this as error to messages. t.delete() return try: t.save() except IntegrityError: # fails because title/artist/album already in db. # TODO add this as warning to messages. t.delete() return # add to the playlist playlist.tunes.add(t) playlist.save() return
def test_file_reading(testfile, expected): filename = os.path.join(testfolder, testfile) # print(filename) tag = TinyTag.get(filename) for key, expected_val in expected.items(): result = getattr(tag, key) fmt_string = 'field "%s": got %s (%s) expected %s (%s)!' fmt_values = (key, repr(result), type(result), repr(expected_val), type(expected_val)) if key == 'duration' and result is not None and expected_val is not None: # allow duration to be off by 100 ms and a maximum of 1% if abs(result - expected_val) < 0.100: if expected_val and min(result, expected_val) / max( result, expected_val) > 0.99: continue assert result == expected_val, fmt_string % fmt_values undefined_in_fixture = {} for key, val in tag.__dict__.items(): if key.startswith('_') or val is None: continue if key not in expected: undefined_in_fixture[key] = val assert not undefined_in_fixture, 'Missing data in fixture \n%s' % str( undefined_in_fixture)
def sendTrackClient(): lsDataTracks = [] lsTracks = [] # Este for lee el directorio raiz, sus subcarpetas y archivos. El metodo walk sirve para leer un directorio for root, dirs, files, in os.walk("musica\\cliente2\\canciones2\\"): for name in files: # Si extension del archivo es tipo musica agregamos a lista if name.endswith((".mp3", ".mp4a", ".flac", ".alac", ".wav", ".wma", ".ogg")): try: # Creamos un objeto tinyTag por cada cancion y obtenemos sus metadatos y los guardamos en una lista temp_track = TinyTag.get(root + "\\" + name) try: file = open("musica\\cliente2\\canciones2\\" + name, "rb") file_data = file.read() except: print("Error al leer archivo") file.close() # Creamos una lista con los metadatos de cada cancion y agregamos estas listas a otra lista para tener una matriz de canciones lsDataTracks = [name, temp_track.title, temp_track.artist, file_data, temp_track.album] lsTracks.append(lsDataTracks) except TinyTagException: print("Error. No se puede leer el archivo.") # print("\nLISTA DE CANCIONES: ", lsTracks) return lsTracks
async def fb_sfx(self, message, url): try: tag = TinyTag.get(url) except TinyTagException: return # Connection check if message.guild.voice_client is None: if message.author.voice: await message.author.voice.channel.connect() if message.guild.id not in self.players: self.players[message.guild.id] = audioplayer.AudioPlayer( self.client, message) else: return await message.send( "You're not in a voice channel, silly. :eyes:") elif message.author.voice.channel != message.guild.voice_client.channel: return await message.send( "Come in here if you want me to play something. :eyes:") if tag.title is None: tag.title = url[url.rfind("/") + 1:] track = {"title": tag.title, "url": url, "track_type": "sfx"} if message.guild.id not in self.players: self.players[message.guild.id] = audioplayer.AudioPlayer( self.client, message) await self.players[message.guild.id].queue.put(track)
def _fetch_embedded_image(self, path): filetypes = ('.mp3',) max_tries = 3 header, data, resized = None, '', False try: files = os.listdir(path) files = (f for f in files if f.lower().endswith(filetypes)) for count, file_in_dir in enumerate(files, start=1): if count > max_tries: break filepath = os.path.join(path, file_in_dir) try: tag = TinyTag.get(filepath, image=True) image_data = tag.get_image() except IOError: continue if not image_data: continue _header, _data = self.resize_image_data( image_data, (self.IMAGE_SIZE, self.IMAGE_SIZE)) if _data: header, data, resized = _header, _data, True break except OSError: pass return header, data, resized
def get(cls, filename, tags=True, duration=True): parser_class = None size = os.path.getsize(filename) if not size > 0: return TinyTag(None, 0) if cls == TinyTag: """choose which tag reader should be used by file extension""" mapping = { ('.mp3', ): ID3, ('.oga', '.ogg'): Ogg, ('.wav'): Wave, ('.flac'): Flac, } for fileextension, tagclass in mapping.items(): if filename.lower().endswith(fileextension): parser_class = tagclass else: # use class on which the method was invoked as parser parser_class = cls if parser_class is None: raise LookupError('No tag reader found to support filetype! ') with open(filename, 'rb') as af: tag = parser_class(af, size) tag.load(tags=tags, duration=duration) return tag
def addSong(path, playlistName): tag = TinyTag.get(path) name = tag.title artist = tag.artist album = tag.album date = tag.year genre = tag.genre length = int(tag.duration) / 60 c.execute( """INSERT INTO Songs (Name, Artist, Album, DateofIt, Genre, Length, Path) VALUES(?, ?, ?, ?, ?, ?, ?)""", (name, artist, album, date, genre, length, path)) a = IDofPlaylist(playlistName) c.execute( """INSERT INTO PlaylistsSongs (NameOfSong, PlaylistID) values(?, ?)""", (name, a)) c.execute("SELECT EXISTS(SELECT 1 FROM Albums WHERE Name = ? LIMIT 1)", (album, )) record = c.fetchone() if record[0] == 1: print(album) print("Name is in the table") else: print(album) print("Name not in table") addAlbum(album, artist) idd = IDofAlbum(album) c.execute( """INSERT INTO AlbumsSongs (NameOfSong, AlbumID) values(?, ?)""", (name, idd)) s = sum(idd, True) c.execute("""UPDATE Albums SET NOofSongs = ? WHERE ID = ?""", (s, idd))
def add_items(self, value): if isinstance(value, str): fp = value else: fp = f'{dirpath}\\{self.playlistWidget.itemFromIndex(value).text()}' playlist = m3u_parser.load(filepath=fp) self.listWidget.clear() Data.filelist = [] Data.streamlist = [] if playlist.files: for i in playlist.files: tag = TinyTag.get(i.file) Data.filelist.append(i.file) if tag.title != '' and tag.artist != '': self.listWidget.addItem(f'{tag.artist} - {tag.title}') elif tag.title and tag.artist == '': self.listWidget.addItem(tag.title) else: self.listWidget.addItem(i) if playlist.urls: for i in playlist.urls: Data.streamlist.append(i.url) Data.pics.append(i.picture) self.listWidget.addItem(i.title) self.listWidget.setCurrentRow(0)
def parseFilename(filename): #check out id3 for recently downloaded files try: newfilename = TinyTag.get(sourceDir + filename).title if newfilename and newfilename is not None: log_info("Filename " + filename + " parsed to ") filename = newfilename except Exception as e: log_error(e, "parseFileName while parsing " + filename) try: filename = filename[re.search("[a-zA-Z]", filename).start():] except Exception as e: log_error( e, "parseFileName after parsing " + filename + " to " + newfilename) filename = re.sub(r'\([^)]*\)', '', filename) filename = re.sub(r'\[[^\]]*\]', '', filename) filename = re.sub(r'(?i)(www.(.*).com)', '', filename) filename = re.sub(r'(?i)(www.(.*).eu)', '', filename) filename = re.sub(r'(?i)(www.(.*).pk)', '', filename) filename = filename.split(',')[0] filename = filename.split('.mp3')[0] filename = re.sub(r'[-+_.]', ' ', filename) filename = re.sub(r' +', ' ', filename).strip() log_info(filename) return filename
def upload_file(): if request.method == 'POST': f = request.files['file'] file_name = f.filename path = os.getcwd() + '\\static\\music\\' path1 = path.replace('\\', '/') path = path1 + file_name f.save(os.path.join(path1, file_name)) username = session['username'] database = 'database.db' conn = sql.connect(database) cur = conn.cursor() row1 = cur.execute("SELECT * FROM users WHERE username = ?", [username]) result1 = cur.fetchone() tag = TinyTag.get(path) album = tag.album title = tag.title artist = tag.artist id = result1[0] if title == None: title = path title = title.rsplit('/', 1)[-1] i_sql = "insert into songs(title,path,album,artist,user_id) values (?,?,?,?,?)" val = (title, path, album, artist, id) cur.execute(i_sql, val) conn.commit() conn.close() return redirect(url_for('dashboard')) else: return redirect(url_for('dashboard'))
def convert_and_get_data(src_path, dst_path): current_dir = [(os.path.join(src_path, element), element) for element in os.listdir(src_path) if not element.startswith('.')] for path, element in current_dir: if os.path.isdir(path): # Recursively perform song conversion for all songs in directory convert_and_get_data(path, dst_path) elif os.path.isfile(path) and path.endswith(('.mp3', '.wav')): perform_copy = True dst = dst_path try: # Retrieve genre from song metadata using tinytag genre = format_string(TinyTag.get(path).genre).replace('\x00', '') logging.info(genre) except TinyTagException: # Do not retain the song if an exception is raised retrieving the genre perform_copy = False else: if not include_condition(mode, genre): # Do not retain the song if its genre is not one contained in one of the defined classes perform_copy = False finally: # If song is to be retained, then copy it to the new directory, if not already there. Avoids editing raw dataset. if perform_copy: if not os.path.exists(os.path.join(dst, element)): copy2(path, dst)
def getMetaData(fullname, playlists): log.info('accessing metadata...') index = 0 tagInfo = [] for track in playlists: name= playlists[track] if os.path.isfile(name): try: filename = os.path.basename(name) log.success('-------------------------') tag = TinyTag.get(name) if tag.title != '' or tag.artist != '': song = str(tag.title+':'+tag.artist) tagInfo.append(song) log.warn('tag info:', filename.encode("ascii", "ignore")) log.info('Artist:', tag.artist) log.info('Album:', tag.album) log.info('Title:', tag.title.encode("ascii", "ignore")) log.info('Track number:', tag.track) index += 1 else: log.warn('WARN: no id3 info provide') except Exception as e: log.err("An error occurred while getting metadata of the file:", name) log.err("Error:", e) else: log.err("The file: %s does not exist, check the path or filename" % (name)) print log.err('track processing:', str(index)) saveMetaData(fullname, tagInfo, index) return tagInfo
def full(file): tag = TinyTag.get(file) audio = FLAC(file) # Get minutes and seconds m, s = divmod(int(audio.info.length), 60) h, m = divmod(m, 60) print BOLD + "Album:" + END, tag.album print BOLD + "Album artist:" + END, tag.albumartist print BOLD + "Artist:" + END, tag.artist print BOLD + "Audio offset:" + END, tag.audio_offset print BOLD + "Bitrate:" + END, int(tag.bitrate), "kbps" print BOLD + "Channels:" + END, audio.info.channels print BOLD + "Disc:" + END, tag.disc print BOLD + "File:" + END, os.path.basename(file) print BOLD + "Filesize:" + END, round((float(tag.filesize) / 1024) / 1024, 2), "MiB" print BOLD + "Genre:" + END, tag.genre # Minutes and seconds if h > 0: print BOLD + "Length:" + END, "%02dh %02dm %02ds" % (h, m, s) else: print BOLD + "Length:" + END, "%02dm %02ds" % (m, s) print BOLD + "Title:" + END, tag.title print BOLD + "Track:" + END, tag.track print BOLD + "Year:" + END, tag.year
def collect(self): folder_queue = [self.parser.source] home_path_len = len(folder_queue[0]) while (len(folder_queue) > 0): current_folder = folder_queue[0] folder_queue = folder_queue[1:] if len(current_folder[home_path_len:]) == 0: print("[+] Scan /") else: print("[+] Scan {}".format(current_folder[home_path_len:])) files, folders = get_content(current_folder) # skip folder named '.folder' # generate full path for folder in folders: if folder[0] != '.': full_path = current_folder + '/' + folder folder_queue.append(full_path) # work with files for f in files: try: fp = current_folder + '/' + f # full path to file tag = TinyTag.get(fp) except LookupError: continue except: print("Cannot get tag from file --> Skip\n\t{}".format(fp)) continue self.sort(fp, tag)
def get_tags(track_list, src_dir=os.getcwd(), dst_dir=os.getcwd()): for music in track_list: music_path = os.path.join(src_dir, music) song = TinyTag.get(music_path) if song.artist and song.album: if song.title is None: name = music else: name = song.artist + "-" + song.title + "-" + song.album + ".mp3" path_after = os.path.join(dst_dir, song.artist) try: os.mkdir(path_after) path_after = os.path.join(path_after, song.album) try: os.mkdir(path_after) path_after = os.path.join(path_after, name) os.rename(music_path, path_after) print(music_path, "->", path_after) except OSError: path_after = os.path.join(path_after, name) os.rename(music_path, path_after) print(music_path, "->", path_after) except OSError: path_after = os.path.join(path_after, song.album) try: os.mkdir(path_after) path_after = os.path.join(path_after, name) os.rename(music_path, path_after) print(music_path, "->", path_after) except OSError: path_after = os.path.join(path_after, name) os.rename(music_path, path_after) print(music_path, "->", path_after) else: print("Отсутсвует тег у файла", music)
def get_audio_duration(f): # try: # x = mutagen.mp3.MP3(f) # res = x.info.length # return res # except mutagen.mp3.HeaderNotFoundError: # return 0 try: tag = TinyTag.get(f) duration = tag.duration if duration is None: raise Exception() return duration except: output = '/tmp/gen_podcast_rss_mp3_duration.txt' cmd = """ffprobe "%s" 2>&1 | grep Duration | awk '{print(substr($2, 0, 8));}' > %s""" % ( f, output) # print(cmd) os.system(cmd) with open(output) as fh: text = fh.read() text = text.split(':') try: return 3600 * int(text[0]) + 60 * int(text[1]) + int(text[2]) except: return 0
def status(): global pifm_proc global playing_file global start_time running = pifm_proc and not pifm_proc.poll() if not running: return jsonify({ "running": False, }), 200 file = playing_file f = TinyTag.get("static/audio/" + file, image=True) if not f.title: f.title = file img_exists = os.path.isfile("static/img/" + file.split(".")[0] + ".png") if img_exists: img_path = file.split(".")[0] + ".png" else: img_path = None return jsonify({ "running": True, "filename": file, "name": f.title, "length": f.duration, "author": f.artist, "img": img_path, "time_elapsed": time.time() - start_time, }), 200
def form_valid(self, form): song = TinyTag.get(self.request.FILES['song'].file.name) #form.instance.audio_id = generate_key(15, 15) form.instance.user = self.request.user form.instance.playtime = song.duration form.instance.size = song.filesize artists = [] for a in self.request.POST.getlist('artists[]'): try: artists.append(int(a)) except: artist = Artist.objects.create(name=a) artists.append(artist) form.save() form.instance.artists.set(artists) form.save() data = { 'status': True, 'message': "Successfully submitted form data.", 'redirect': reverse_lazy('core:upload-details', kwargs={'audio_id': form.instance.audio_id}) } return JsonResponse(data)
def db_check(): mp3s = get_mp3_list() for d, mp3 in mp3s: fullpath = os.path.join(d,mp3) data = db_get(fullpath, 'fullpath') if not data: print 'adding: ', fullpath data = { 'fullpath': fullpath, 'title': mp3, 'description': '', } try: date_part = mp3.split('.')[0] date_obj = datetime.strptime(date_part, '%Y-%m-%d_%H-%M-%S') #data['date'] = datetime.strftime(date_obj, '%a %b %d, %Y at %I:%M %p') data['date'] = date_obj except: date_obj = datetime.fromtimestamp(os.path.getctime(fullpath)) #data['date'] = datetime.strftime(date_obj, '%a %b %d, %Y at %I:%M %p') data['date'] = date_obj tag = TinyTag.get(fullpath) m, s = divmod(tag.duration, 60) h, m = divmod(m, 60) data['duration'] = "%d:%02d:%02d" % (h, m, s) db_insert(data) delete = [] for mp3 in db_get_all(): if not os.path.exists(mp3['fullpath']): delete.append(mp3['fullpath']) for d in delete: print 'removing: ', d db_remove(d)
def folderTraversal(self, folderPath): for root, subdir, files in os.walk(folderPath): hasMusic = False albumName = "" for f in files: fullPath = os.path.join(root, f) try: metadata = TinyTag.get(fullPath) except LookupError: # File is not a valid audio file, skip continue metadata.album = str(metadata.album) self.trackIDList.add(utils.genID(metadata)) if self.config.filter.check(metadata) and not (metadata in self.record): albumName = metadata.album if albumName not in self.albums: self.albums[albumName] = objects.Album(albumName) newTrack = objects.Track(metadata, fullPath) self.albums[albumName].add(newTrack) hasMusic = True self.progress.incTotal() if hasMusic: # Handle cover image self.albums[albumName].coverFile = self.__detectCoverFile(root) logging.info("Album: %s with %d song(s)" % (albumName, len(self.albums[albumName].tracks)))
def __init__(self, path): tags = TinyTag.get(path, duration=False) self.path = pathlib.Path(path) self.title = tags.title self.album = tags.album self.artist = tags.artist self.track = parse_tracknumber(tags.track)
def _fetch_embedded_image(self, path): filetypes = ('.mp3', ) max_tries = 3 header, data, resized = None, '', False try: files = os.listdir(path) files = (f for f in files if f.lower().endswith(filetypes)) for count, file_in_dir in enumerate(files, start=1): if count > max_tries: break filepath = os.path.join(path, file_in_dir) try: tag = TinyTag.get(filepath, image=True) image_data = tag.get_image() except IOError: continue if not image_data: continue _header, _data = self.resize_image_data( image_data, (self.IMAGE_SIZE, self.IMAGE_SIZE)) if _data: header, data, resized = _header, _data, True break except OSError: pass return header, data, resized
def rename_album(self, name, exclude): exclude = [exclude, self.Band] old_name = name name = basename(name) for word in exclude: if len(name) > len(word) * 2: name = name.replace(word, '', 1) words = [word.title() for word in split('[ -]', name) if word] try: datetime.strptime(words[0], '%Y') name = ' '.join([' - '.join(words[:2])] + words[2:]) except ValueError: for title in glob(join(old_name, '*')): try: tag = TinyTag.get(title) name = None if tag.year is not None: print tag.year, words name = ' '.join([' - '.join([tag.year, words[0]])] + words[1:]) break except LookupError: pass name = join(self.FileDir, name) if old_name != name: print '{0} -> {1}'.format(old_name, name) move(old_name, name) return name
def __init__(self, csv_path, win_length, hop_length, num_frames): self.clip_length = (num_frames-3) * hop_length + win_length self.data = defaultdict(list) with open(csv_path) as f: for speaker_id, filepath in csv.reader(f, delimiter=' '): self.data[speaker_id].append(filepath) speaker_list = sorted(list(self.data.keys())) self.index2speaker = {ind: spk for ind, spk in enumerate(speaker_list)} self.speaker2index = {spk: ind for ind, spk in enumerate(speaker_list)} # read file sizes if os.path.exists('filesize.json'): with open('filesize.json') as f: self.filesize = json.load(f) else: print('read file tags...') self.filesize = {} for file_list in tqdm(self.data.values()): for filepath in file_list: tag = TinyTag.get(filepath) filesize = int(tag.duration * tag.samplerate) self.filesize[filepath] = filesize with open('filesize.json', 'w') as f: json.dump(self.filesize, f)
def file_list(): payload = {} # p = subprocess.Popen("ls", stdout=subprocess.PIPE, shell=True, cwd="static/audio") # p.wait() # files = p.stdout.readlines() # files = [x.strip() for x in files] i = 0 for r, d, f in os.walk("static/audio"): for f2 in f: try: file = f2 f = TinyTag.get("static/audio/" + file, image=True) if not f.title: f.title = file img_exists = os.path.isfile("static/img/" + file.split(".")[0] + ".png") if img_exists: img_path = file.split(".")[0] + ".png" else: img_path = None payload[i] = { "filename": file, "name": f.title, "length": f.duration, "author": f.artist, "img": img_path } i += 1 except: pass return jsonify(payload)
def test_duration_with_vlc(self): import vlc v = vlc.Instance() mp = MusicPlayer(self.config) albums = mp.get_albums_and_songs() # VLC Start start_time = time.time() for album in albums: print(colorstring("Album: " + album.title, Colors.GREEN)) for song in album.getsonglist(): print(colorstring("\t" + str(song.title), Colors.BLUE)) media = v.media_new(song.filepath) media.parse() print("\tsong duration: " + str(media.get_duration())) print(colorstring("--- VLC took %s seconds ---" % round((time.time() - start_time), 5), Colors.RED)) # VLC End # TinyTag Start start_time = time.time() for album in albums: print(colorstring("Album: " + album.title, Colors.GREEN)) for song in album.getsonglist(): print(colorstring("\t" + str(song.title), Colors.BLUE)) tinytag = TinyTag.get(song.filepath, False, True) print("\tsong duration: " + str(round(tinytag.duration * 1000))) print(colorstring("--- TinyTag took %s seconds ---" % round((time.time() - start_time), 5), Colors.RED))
def getSongInfo(filepath): tag = TinyTag.get(filepath) # make sure everthing returned (except length) is a string for attribute in ['artist','album','title','track']: if getattr(tag, attribute) is None: setattr(tag, attribute, '') return Metainfo(tag.artist, tag.album, tag.title, str(tag.track), tag.length)
def playonce( flist: T.List[Path], image: Path, site: str, inifn: Path, shuffle: bool, usemeta: bool, yes: bool, ): if shuffle: random.shuffle(flist) caption: T.Union[str, None] for f in flist: if usemeta and TinyTag: try: caption = meta_caption(TinyTag.get(str(f))) print(caption) except LookupError: caption = None else: caption = None s = FileIn(inifn, site, infn=f, loop=False, image=image, caption=caption, yes=yes) s.golive()
def find_lyric(path_to_music_file): from tinytag import TinyTag as ttag import xml.etree.ElementTree as ET import base64 try: tag = ttag.get(path_to_music_file) except: print('Tag read error') return '' album = tag.album artist = tag.artist title = tag.title [lyrics_type, lyrics_base64] = get_lyric_base64(album, artist, title, 3) if lyrics_type == '2': [lyrics_type, lyrics_text_base64] = get_lyric_base64(album, artist, title, 1) print('lyric added from line sync source') return lsy_decoder(lyrics_base64, lyrics_text_base64) elif lyrics_type == '3': lyrics_petitlyricform = base64.b64decode(lyrics_base64).decode("UTF-8") lyrics_tree = ET.fromstring(lyrics_petitlyricform) lyric_string = '[00:00.00] (petitlyric_wsy)\n' for line in lyrics_tree.findall('line'): timepoint = line.find('word').find('starttime').text lyric_line = line.find('linestring').text if lyric_line is None: lyric_line = '' lyric_string += ms2mmss(timepoint) + ' ' + lyric_line + '\n' print('lyric added from word sync source') return lyric_string return ''
def playing(self): self.stopTheMusic = False # start first track self.tracks_number = len(self.playlist) NEXT = pygame.USEREVENT + 1 # get the right speed of each song audiofile = TinyTag.get(self.playlist[self.current_track]) pygame.mixer.init(frequency=audiofile.samplerate) print('-------------------------------------------------------------------') # sometimes needed I dont know why but on my rasp 4 I dont need this line anymore try: screen = pygame.display.set_mode((400, 300)) except Exception as ex: print('error but that is fine') print('-------------------------------------------------------------------') print(self.playlist) # start first track pygame.mixer.music.load(self.playlist[self.current_track]) pygame.mixer.music.play() pygame.mixer.music.set_endevent(NEXT) self.running = True while pygame.mixer.music.get_busy(): nothing = True if self.stopTheMusic == False: self.next()
def cli(directory, recursive, auth, scrobble_from): if auth: authorize() exit() if directory: mp3_files = get_mp3_files(directory, recursive) if mp3_files: with open(generate_filename(), 'a+') as f: for file in sorted(mp3_files): tag = TinyTag.get(file) track = f'{tag.artist} | {tag.title} | {tag.album}' click.echo(track) f.write(f'{track}\n') else: click.echo('No mp3 files found in provided directory') if scrobble_from: lastfm = authorize() scrobbles = generate_scrobbles(scrobble_from) if scrobbles: for metainfo, track_time in scrobbles.items(): artist, title, album = metainfo.split(' | ') lastfm.scrobble(artist=artist, title=title, album=album, timestamp=track_time)
def get_metadata_from_music_dir( config: Config, song_list: bool = True) -> Dict[str, Union[Row, TinyTag]]: music_dir = config.music_dir paths = glob.glob(f"{music_dir}/**/*", recursive=True) metadata = {} row_keys = {f.name for f in fields(Row)} for path in paths: try: metadata[path] = TinyTag.get(path, image=True) except TinyTagException as e: pass if path not in metadata or not metadata[path].duration: md = ffprobe_metadata(path) if config.use_ffprobe else { "filename": path } if not md: continue md = {key: value for key, value in md.items() if key in row_keys} metadata[path] = Row(**md) date_re = re.compile(config.date_regex) for path, tags in metadata.items(): match = date_re.search(path) date = "{year}-{month}-{day}".format( **match.groupdict()) if match else "" tags.date = date if date not in config.ignored_dates else None return metadata
def main(): args = parser.parse_args() args.foldername = os.path.expanduser(args.foldername) new_foldername = args.foldername # keep a list of all cues and flacs file_lists = get_music(new_foldername=new_foldername) music_filenames = file_lists['mp3'] # now, for each file, get the mp3 tags and get the date created music_dataframe = [] for music_file in music_filenames: try: tag = TinyTag.get(music_file) except Exception as e: print e next if tag.artist is not None: artist = tag.artist.encode('ascii', 'ignore') if tag.album is not None: album = tag.album.encode('ascii', 'ignore') if tag.title is not None: title = tag.title.encode('ascii', 'ignore') date_changed = os.path.getmtime(music_file) music_dataframe.append({'artist':artist,'album':album,'title':title,'date':date_changed}) music_dataframe = DataFrame(music_dataframe) music_dataframe.to_csv("mp3_tags.csv")
def updateInternal(self): db = firebasePyre.database() internal = 1 for files in os.listdir(musicFolder): #print(files) tag = TinyTag.get("/home/pi/Music/" + files) artist = tag.artist songName = tag.title duration = tag.duration votes = 0 Firebase.patch("/Rooms/00001",{artist + "-" +songName:duration}) Firebase.patch("/Rooms/00001/" + artist + "-" + songName,{"votes":votes}) Firebase.patch("/Rooms/00001/" + artist + "-" + songName,{"title":songName}) Firebase.patch("/Rooms/00001/" + artist + "-" + songName,{"artist":artist}) Firebase.patch("/Rooms/00001/" + artist + "-" + songName,{"playNext":"false"}) Firebase.patch("/Rooms/00001/" + artist + "-" + songName,{"duration":duration}) Firebase.patch("/Rooms/00001/voters",{"placeholder":"voted"}) songs = db.child("Rooms").child("00001").get() highestVote = 0 for song in songs.each(): print(song) if song.val().get("votes") > highestVote: highestVote = song.val().get("votes") print("highest vote is" + highestVote) else: print("no votes")
def api_fetchalbumart(self, directory): _save_and_release_session() default_folder_image = "../res/img/folder.png" log.i('Fetching album art for: %s' % directory) filepath = os.path.join(cherry.config['media.basedir'], directory) if os.path.isfile(filepath): # if the given path is a file, try to get the image from ID3 tag = TinyTag.get(filepath, image=True) image_data = tag.get_image() if image_data: log.d('Image found in tag.') header = {'Content-Type': 'image/jpg', 'Content-Length': len(image_data)} cherrypy.response.headers.update(header) return image_data else: # if the file does not contain an image, display the image of the # parent directory directory = os.path.dirname(directory) #try getting a cached album art image b64imgpath = albumArtFilePath(directory) img_data = self.albumartcache_load(b64imgpath) if img_data: cherrypy.response.headers["Content-Length"] = len(img_data) return img_data #try getting album art inside local folder fetcher = albumartfetcher.AlbumArtFetcher() localpath = os.path.join(cherry.config['media.basedir'], directory) header, data, resized = fetcher.fetchLocal(localpath) if header: if resized: #cache resized image for next time self.albumartcache_save(b64imgpath, data) cherrypy.response.headers.update(header) return data elif cherry.config['media.fetch_album_art']: #fetch album art from online source try: foldername = os.path.basename(directory) keywords = foldername log.i(_("Fetching album art for keywords {keywords!r}").format(keywords=keywords)) header, data = fetcher.fetch(keywords) if header: cherrypy.response.headers.update(header) self.albumartcache_save(b64imgpath, data) return data else: # albumart fetcher failed, so we serve a standard image raise cherrypy.HTTPRedirect(default_folder_image, 302) except: # albumart fetcher threw exception, so we serve a standard image raise cherrypy.HTTPRedirect(default_folder_image, 302) else: # no local album art found, online fetching deactivated, show default raise cherrypy.HTTPRedirect(default_folder_image, 302)
def test_pathlib_compatibility(): try: import pathlib except ImportError: return testfile = next(iter(testfiles.keys())) filename = pathlib.Path(testfolder) / testfile tag = TinyTag.get(filename)
def get_node(filename): from tinytag import TinyTag logger.debug(filename) try: tag = TinyTag.get(filename) logger.info(tag.title) except LookupError as err: logger.error("File `{0}` processing error: {1}".format(filename, err))
def __init__(self, ruta, titulo = "Cancion desconocida", artista = "Autor desconocido"): self.ruta = ruta datos = TinyTag.get(ruta) self.artista = artista self.titulo = titulo if datos.title: self.titulo = datos.title if datos.artist: self.artista = datos.artist
def genMoodHist(fileName, inputFile, outputFile, localOutput): countsR = initCounts() countsG = initCounts() countsB = initCounts() while True: byte = inputFile.read(3) if len(byte) == 3: countsR[int(ord(byte[0]) / 23)] += 1 countsG[int(ord(byte[1]) / 23)] += 1 countsB[int(ord(byte[2]) / 23)] += 1 else: break for binIdx in range(12): xMin = binIdx * 23 xMax = xMin + 22 localOutput.write(str(xMin) + "-" + str(xMax) + ";") localOutput.write("\n") writeHist(countsR, localOutput) writeHist(countsG, localOutput) writeHist(countsB, localOutput) try: tag = TinyTag.get(fileName[:-5] + ".mp3") if tag.bitrate < 512: br = int(round(tag.bitrate)) else: br = int(round(tag.bitrate/1000)) outputFile.write(fileName + ";" + str(br) + ";") table = [] ct = 0; with open(fileName[:-5] + ".csv", 'r') as fd: for line in fd: table.append(line.strip().split(";")) ct += 1; for i in range(0,3): subtotal = float(0) for rgb in table: subtotal += pow(int(rgb[i]), 2) subtotal /= ct outputFile.write(str(subtotal) + ";") outputFile.write(str(getCountsMax(countsR)) + ";" + str(getCountsMax(countsG)) + ";" + str(getCountsMax(countsB)) + "\n") except OSError as ose: print("Error: " + str(ose)) return (1) return (0)
def get_artist(path): musicMeta = TinyTag.get(path) artist = musicMeta.artist if artist is not None: artist = ''.join(i for i in artist if i not in string.punctuation).replace(" ", "") if artist is None or not artist or artist.isspace(): return "Unknown" else: return artist
def getTag(song_path): #returns all matching fields tag = TinyTag.get(song_path) tag_fields = tag.__dict__ details = {} for item in tag_fields: if item in fields and tag_fields[item] != None: details[item] = tag_fields[item] details['duration'] = "{:.2f}".format(details.get('duration')) if details.get('bitrate') > 5000: details.pop('bitrate') return details
def tags_wav(name, infer=True): try: tags = TinyTag.get(name) except struct.error: if infer: uprint('WARN: Corrupted or mistagged, inferring artist and album: %s ...' % name, end=' ') return infer_album_artist(name) return None if not tags: return None, None return tags.artist, tags.album
def get_info(testfile, expected): filename = os.path.join(samplefolder, testfile) print(filename) tag = TinyTag.get(filename) for key, value in expected.items(): result = getattr(tag, key) fmt_string = 'field "%s": got %s (%s) expected %s (%s)!' fmt_values = (key, repr(result), type(result), repr(value), type(value)) assert result == value, fmt_string % fmt_values print(tag) print(tag.__repr__())
def __init__(self, title: str, filepath: str): super(SongModel, self).__init__() self.id = id(self) self.title = title self.filepath = filepath # This operation can go wrong when another program is using the filepath try: self._tags = TinyTag.get(self.filepath, False, True) self.duration = round(self._tags.duration) except PermissionError as e: self.duration = None print(e)
def moves_record(): """-""" input_file = "../audio/show1/01_m.mp3" tag = TinyTag.get(input_file) track_length = tag.duration if os.path.exists(input_file + ".moves"): os.remove(input_file + ".moves") output_file = open(input_file + ".moves", "w") pygame.init() pygame.mixer.init() pygame.mixer.music.load(input_file) print "Playing " + input_file print "3... " time.sleep(1) print "2... " time.sleep(1) print "1... " time.sleep(1) pygame.mixer.music.play() start_time = time.time() last_time = 0 is_done = False do_extra_close = False create_output(output_file, '{ "moveitem": [') while (is_done != True) and ((time.time() - start_time) < track_length): command = "" next_char = getch() current_time = time.time() - start_time if do_extra_close: create_output( output_file, str(' { "time":%.2f, "command":"%s" },' % ((current_time + last_time) / 2, "CLOSE")) ) do_extra_close = False if next_char == "q": is_done = True else: if next_char == "i": # This means OPEN_THEN_CLOSE command = "OPEN" do_extra_close = True if next_char == "o": command = "OPEN" if next_char == "p": command = "CLOSE" if command != "": create_output(output_file, str(' { "time":%.2f, "command":"%s" },' % (current_time, command))) last_time = current_time create_output(output_file, str(' { "time":%.2f, "command":"CLOSE" }\n] }' % track_length)) output_file.close()
def copland_scrape(): event_list = Event.objects.filter(start_date__gt=date(2013, 11, 22)).order_by('start_date') event_list = event_list.reverse() text_file = open("copland.txt", "w") fstring = "" for e in event_list: print(e.name) fstring += e.start_date.strftime("%m.%d.%y") + ": " + e.name program = Program.objects.select_related().filter(event = e).order_by('position') performers = Performer.objects.select_related().filter(event = e).order_by('position') recs = EventAudioRecording.objects.select_related().filter(event = e).order_by('position') dur = "" for i in range(len(program)): work = program[i].works.all()[0] if len(recs) > 0 and os.path.isfile(recs[i].compressed_master_recording.path): #mf = mad.MadFile(recs[i].compressed_master_recording.path) #dur = int(mf.total_time() / 1000) #dur = str(timedelta(seconds=dur)) #fname = recs[i].uncompressed_master_recording.path #print(fname) #with contextlib.closing(wave.open(fname,'r')) as f: # frames = f.getnframes() # rate = f.getframerate() # duration = math.floor(frames / float(rate)) # minutes, seconds = divmod(duration, 60) # hours, minutes = divmod(minutes, 60) # dur = str(hours) + ":" + str(minutes) + ":" + str(seconds) tag = TinyTag.get(recs[i].compressed_master_recording.path) duration = tag.duration print(duration) minutes, seconds = divmod(duration, 60) hours, minutes = divmod(minutes, 60) dur = str(int(hours)) + ":" + str(int(minutes)) + ":" + str(int(seconds)) else: dur = "????" fstring += "\n"+work.name + " by " + work.authors.all()[0].name + "* - " + dur if len(performers) > 0: fstring += "\nperformers: " for p in performers: fstring += p.performer.name + " - " for i in p.instruments.all(): fstring += i.name + ", " fstring = fstring[:-2] fstring += "; " fstring = fstring[:-2] fstring += "\n\n" text_file.write(fstring.encode('utf-8')) text_file.close()
def get_encode_task(source_file, destination, bitrate): tags = TinyTag.get(source_file) track_relative_path = get_track_relative_path(tags) if track_relative_path: track_absolute_path = os.path.join(destination, track_relative_path) if not os.path.exists(track_absolute_path): return { 'source': source_file, 'destination': track_absolute_path, 'destination_rel': track_relative_path, 'bitrate': bitrate } else: print('Ignoring ' + source_file)
def _get_duration_of(filename): """Return the duration of the media file located at ``filename``. Use :meth:`.Media.populate_duration_from` if you want to populate the duration property of a Media instance using a local file. :param filename: Path to the media file which shall be used to determine this media's duration. The file extension must match its file type, since it is used to determine what type of media file it is. For a list of supported formats, see https://pypi.python.org/pypi/tinytag/ :type filename: str :returns: datetime.timedelta """ return datetime.timedelta(seconds=TinyTag.get(filename).duration)
def get_info(testfile, expected): filename = os.path.join(testfolder, testfile) print(filename) tag = TinyTag.get(filename) for key, expected_val in expected.items(): result = getattr(tag, key) if key == 'duration': # allow duration to be off by 100 ms and a maximum of 1% if abs(result - expected_val) < 0.100: if expected_val and min(result, expected_val) / max(result, expected_val) > 0.99: continue fmt_string = 'field "%s": got %s (%s) expected %s (%s)!' fmt_values = (key, repr(result), type(result), repr(expected_val), type(expected_val)) assert result == expected_val, fmt_string % fmt_values
def __init__(self, ruta, titulo='Cancion desconocida', artista='Autor desconocido'): # Usar TinyTag para obtener la informacion de la cancion, sobreescribir con lo pasado por # parametro solo si la informacion no se encuentra disponible self.ruta = ruta tag = TinyTag.get(ruta) get_titulo = tag.title get_artista = tag.artist if get_titulo: self.titulo = tag.title else: self.titulo = titulo if get_artista: self.artista = tag.artist else: self.artista = artista
def parse_metadata(self): # Errors with some mp3 files try: tag = TinyTag.get(str(self.absolute_path())) self.meta_track = tag.track.zfill(2) if tag.track else None self.meta_track_total = tag.track_total self.meta_title = tag.title self.meta_artist = tag.artist self.meta_album = tag.album self.meta_year = tag.year self.meta_genre = tag.genre self.meta_duration = tag.duration except: logger.info('Fail to get meta data from %s', str(self.absolute_path()))
def add(self, path): try: tag = TinyTag.get(path) except: artiste = 'Pas' album = 'de' title = 'chocolat' duration = '!' else: artist = tag.artist album = tag.album title = tag.title duration = int(tag.duration) duration = '{:02}:{:02}'.format(duration / 60, duration % 60) entry = Entry(path, artist, album, title, duration) self.playlist.append(entry)
def cover_art_get(self): if self.playing_type == 'radio': return self._get_cover_from_zip(COVER_ART_RADIO) if self.file == "" : return self._get_cover_from_zip(DEFAULT_COVER) try: tag = TinyTag.get(os.path.join(self.music_directory, self.file), image=True) cover_art = tag.get_image() except: return self._get_cover_from_zip(DEFAULT_COVER) if cover_art is None: return self._get_cover_from_zip(DEFAULT_COVER) bytes_io = io.BytesIO(cover_art) return pygame.image.load(bytes_io)
def cover_art_get(self, dest_file_name="covert_art.jpg"): if self.playing_type == 'radio': return COVER_ART_RADIO if self.filepath == "": return DEFAULT_COVER try: tag = TinyTag.get(os.path.join(self.music_directory, self.file), image=True) cover_art = tag.get_image() except: return DEFAULT_COVER if cover_art is None: return DEFAULT_COVER with open(dest_file_name, 'wb') as img: img.write(cover_art) # write artwork to new image return dest_file_name
def test_get_length(self): taginfo = TinyTag.get(self.samplefiles[0], False, True) print("artist " + str(taginfo.artist)) # artist name as string print("album " + str(taginfo.album)) # album as string print("albumartist " + str(taginfo.albumartist)) # album artist as string print("audio_offset " + str(taginfo.audio_offset)) # number of bytes before audio data begins print("bitrate " + str(taginfo.bitrate)) # bitrate in kBits/s print("disc " + str(taginfo.disc)) # disc number print("disc_total " + str(taginfo.disc_total)) # the total number of discs print("duration (sec) " + str(taginfo.duration)) # duration of the song in seconds print("filesize " + str(taginfo.filesize)) # file size in bytes print("genre " + str(taginfo.genre)) # genre as string print("samplerate " + str(taginfo.samplerate)) # samples per second print("title " + str(taginfo.title)) # title of the song print("track " + str(taginfo.track)) # track number as string print("track_total " + str(taginfo.track_total)) # total number of tracks as string print("year " + str(taginfo.year)) # year or data as string
def get(self, request, path): file_path = Directory.get_basedir().absolute_path() / path if not file_path.exists(): raise NotFound() # try fetching from the audio file if file_path.is_file(): tag = TinyTag.get(str(file_path), image=True) image_data = tag.get_image() if image_data: return ImageResponse(image_data=image_data) # try the parent directory of the file file_path = os.path.dirname(str(file_path)) file_cache_path = pathprovider.album_art_file_path(str(file_path)) if os.path.exists(file_cache_path): logger.debug('Getting cached thumbnail: %s' % file_cache_path) with open(file_cache_path, 'rb') as fh: return ImageResponse(image_data=fh.read()) fetcher = AlbumArtFetcher() header, data, resized = fetcher.fetch_local(str(file_path)) if header: logger.debug('Getting album art from local: %s' % file_path) if resized: with open(file_cache_path, 'wb') as fh: fh.write(data) return ImageResponse(image_data=data) # else: # logger.debug('Getting album art from online source.') # try: # foldername = os.path.basename(file_path) # keywords = foldername # logger.info("Fetching album art for keywords: %s" % keywords) # header, data = fetcher.fetch(keywords) # if header: # with open(file_cache_path, 'wb') as fh: # fh.write(data) # return ImageResponse(image_data=data) # except: # logger.error('Unable to get album art from online source.') raise Http404()