def process_dir(out_list, directory, files): for f in files: path = os.path.join(directory, f) if os.path.isdir(path): return else: ext = f.split('.').pop().lower() metadata = {} if ext == 'mp3': metadata = EasyID3(path) elif ext == 'flac': metadata = FLAC(path) else: return out_data = {'tracknumber': metadata.get('tracknumber', ['0'])[0], 'title': metadata.get('title', ['Untitled'])[0], 'album': metadata.get('album', ['Untitled'])[0], 'artist': metadata.get('artist', ['Unknown'])[0], 'genre': metadata.get('genre', ['Unknown'])[0], 'date': metadata.get('date', ['Unknown'])[0], 'extension': ext, 'path': path} song_path = os.path.join(escape_path(out_data['artist']), escape_path(out_data['album'])) song_name = "%02d-%s" % (int(out_data['tracknumber'].split('/')[0]), escape_path(out_data['title'])) out_data['song_path'] = song_path out_data['song_name'] = song_name out_list.append(out_data)
def getTagInfo(file): ext = file.split(".")[-1] tagsRtn = {} try: if ext.upper() == "MP3": audio = MP3(file) if len( audio ) == 0: return tagsRtn if "title" not in audio.tags.keys() or "artist" not in audio.tags.keys() or "album" not in audio.tags.keys(): return tagsRtn else: tagsRtn['titlaByTag'] = audio.tags['title'][0].upper().strip() tagsRtn['artistByTag'] = audio.tags['artist'][0].upper().strip() tagsRtn['albumByTag'] = audio["album"][0].upper().strip() if "M4A" == ext.upper() : tags = MP4(file) tagsRtn['titlaByTag'] = str( tags.get('\xa9nam')[0] ).upper().strip() tagsRtn['artistByTag'] = str( tags.get('\xa9ART')[0] ).upper().strip() tagsRtn['albumByTag'] = str( tags.get('\xa9alb')[0] ).upper().strip() if "FLAC" == ext.upper() : tags = FLAC(file) tagsRtn['titlaByTag'] = str( tags.get('title')[0] ).upper().strip() tagsRtn['artistByTag'] = str( tags.get('artist')[0] ).upper().strip() tagsRtn['albumByTag'] = str( tags.get('album')[0] ).upper().strip() except Exception as e: logger.debug('Exception:%s', e) logger.debug(traceback.format_exc()) return tagsRtn
def flac_read(fpath): audio = FLAC(fpath) return uni({ 'artist': audio.get('artist', [None])[0], 'album': audio.get('album', [None])[0], 'title': audio.get('title', [None])[0] })
def readflac(filename): read = FLAC(filename) # Create dict containing all meta fields we'll be using. tags = { "ALBUM": read.get('album'), "ALBUMARTIST": read.get('albumartist'), "ARTIST": read.get('artist'), "DATE": read.get('date')[0], "GENRE": read.get('genre'), "TITLE": read.get('title'), "COMMENT": read.get('comment'), "TRACKNUMBER": read.get('tracknumber')[0].zfill(2), "DISCNUMBER": read.get('discnumber') } # Not further looked into this but some FLACs hold a grouping key of contentgroup instead of grouping. tags['GROUPING'] = read.get('grouping') ## If grouping returns None we check contentgroup. # If it still returns none we will ignore it and handle on final checks if tags['GROUPING'] == None: tags['GROUPING'] = read.get('contentgroup') required_tags = ['ALBUM', 'ALBUMARTIST', 'DATE', 'TRACKNUMBER'] for k, v in tags.items(): if v == None: if k in required_tags: print(f"{k} has returned {v}, this is a required tag") sys.exit() return tags
def __song_flac(filename): f = FLAC(filename) artist = f.get("artist", ("",))[0] title = f.get("title", ("",))[0] rating = 0 for k, v in f.iteritems(): if k.startswith("rating"): rating = SongFiles.__adjust_rating_ogg(float(v[0])) break return Song(filename, artist, title, rating)
def parse(file: str) -> Metadata: flac = FLAC(file) checksum = reader.md5(file) return Metadata( flac.get('artist')[0], flac.get('album')[0], file, flac.get('title')[0], flac.get('tracknumber')[0], flac.info.length, checksum)
def find_inconsistent_tags(flac_filepaths, ignore_art=False, ignore_lyrics=False): """Look for missing data in FLAC 'id3' tags or tags that don't match the filename. Positional arguments: flac_filepaths -- list of FLAC file paths to read metadata from. Keyword arguments: ignore_art -- ignore checking if FLAC file has album art embedded in it, boolean. ignore_lyrics -- ignore checking if FLAC file has lyrics embedded in it, boolean. Returns: Dictionary with keys being FLAC file paths and values being a list of warnings to be printed about id3 tags. """ tag_names = ['artist', 'date', 'album', 'tracknumber', 'title'] messages = {p: [] for p in flac_filepaths} for path in flac_filepaths: # Verify filename. split = os.path.splitext(os.path.basename(path))[0].split(' - ') if len(split) != 5: messages[path].append("Filename doesn't have five items.") continue f_artist, f_date, f_album, f_track, f_title = split # Verify basic tags. try: tags = FLAC(path) except flac_error: messages[path].append('Invalid file.') continue t_artist, t_date, t_album, t_track, t_title = [tags.get(i, [''])[0] for i in tag_names] if f_artist != t_artist: messages[path].append('Artist mismatch: {} != {}'.format(f_artist, t_artist)) if f_album != t_album: messages[path].append('Album mismatch: {} != {}'.format(f_album, t_album)) if f_title != t_title: messages[path].append('Title mismatch: {} != {}'.format(f_title, t_title)) # Verify numeric tags. if not f_date.isdigit(): messages[path].append('Filename date not a number.') elif len(f_date) != 4: messages[path].append('Filename date not four digits.') elif f_date != t_date: messages[path].append('Date mismatch: {} != {}'.format(f_date, t_date)) if not f_track.isdigit(): messages[path].append('Filename track number not a number.') elif len(f_track) != 2: messages[path].append('Filename track number not two digits.') elif f_track != t_track: messages[path].append('Track number mismatch: {} != {}'.format(f_track, t_track)) # Check for lyrics and album art. if not ignore_art and not tags.pictures: messages[path].append('No album art.') if not ignore_lyrics and not tags.get('unsyncedlyrics', [False])[0]: messages[path].append('No lyrics.') # Return dict of messages without empty lists. return {k: v for k, v in messages.items() if v}
def _extract(self, path: Path): """ Extract meta-data from music file like name and artists. This method uses mutagen lib to open the file. :param path: Path object with filename :return: List with meta-data """ # Parameters file = None title_tag = "" artist_tag = "" # Return data = { 'title': "", 'artists': "", 'duration': 0.0 } # Check sufix and open music file if path.suffix == '.mp3': # MP3 File file = MP3(path) title_tag = "TIT2" artist_tag = "TPE1" elif path.suffix in ['.m4a', '.mp4']: # MPEG4 File file = MP4(path) title_tag = chr(169) + "nam" artist_tag = chr(169) + "ART" elif path.suffix == '.flac': # FLAC File file = FLAC(path) title_tag = "title" artist_tag = "artist" # Check opening success and read data if file is not None: # Get music title if title_tag in file.keys(): title = file.get(title_tag) data['title'] = (str(title[0] if len(title) > 0 else "")) if isinstance(title, list) else str(title) # Get music artists (separated with '/') if artist_tag in file.keys(): artist = file.get(artist_tag) data['artists'] = "/".join(artist) if isinstance(artist, list) else str(artist) # Get music lenght (seconds) data['duration'] = float(file.info.length) return data
class TagHandler: def __init__(self, filename, **kwargs):#artist=None, album=None, date=None, genre=None): self.tag = FLAC(filename) self.tags = {key:value for key, value in kwargs.iteritems() if value} self._convert_to_int() def _convert_to_int(self): for key, value in self.tags.iteritems(): try: self.tags[key] = int(value) except: continue def prompt(self): for field in ['artist', 'title', 'date', 'album', 'tracknumber']: if not field in self.tags.keys(): if self.tag.get(field, None): self.tags[field] = self.tag[field][0] else: print "Please provide a value for %s" % field self.tags[field] = raw_input("> ") self._convert_to_int() def gen_lame(self): args = ('--ta|"%(artist)s"|--tt|"%(title)s"|--tl|"%(album)s"|--ty|"%(date)s"|--tn|"%(tracknumber)s"' % self.tags).split('|') if self.tags.get('genre', None): args += ['--tg', self.tags['genre']] return args
class Id3tool: ''' class to read/write mp3 tags ''' def __init__(self, fn): ''' allow throw if file not supported ''' if fnmatch.fnmatch(fn, '*.ogg'): self.tag_obj = OggVorbis(fn) elif fnmatch.fnmatch(fn, '*.flac'): self.tag_obj = FLAC(fn) else: self.tag_obj = EasyID3(fn) def save(self): self.tag_obj.save() def readTag(self, tag): if self.tag_obj: tmp = self.tag_obj.get(unicode(tag)) return tmp[0] if tmp else '' else: return '' def writeTag(self, tag, val): self.tag_obj[unicode(tag)] = unicode(val)
def from_flac(f, frame): audio = FLAC(f) lyrics = audio.get(frame) if not lyrics: raise NoLyricsError( "Frame \"{}\" does not contain any lyrics.".format(frame)) lyrics = [x.split("\r\n") for x in lyrics] return lyrics[0]
def check_flac_tags(flac_path): flac = FLAC(flac_path) if not flac.get('artist'): raise Exception(u'Missing artist tag on {0}'.format(flac_path)) if not flac.get('album'): raise Exception(u'Missing album tag on {0}'.format(flac_path)) if not flac.get('title'): raise Exception(u'Missing title tag on {0}'.format(flac_path)) track = flac.get('tracknumber') or flac.get('track') if type(track) in [str, unicode] and '/' in track: track = track.split('/') if type(track) is list: track = track[0] if not track: raise Exception(u'Missing track tag on {0}'.format(flac_path)) disc = flac.get('discnumber') or flac.get('disc') if type(disc) in [str, unicode] and '/' in disc: disc = disc.split('/') if type(disc) is list: disc = disc[0] if disc: return disc, track else: return track,
def get_metadata(self): flac_stat = os.stat(self.flac_path) self.flac_current_mtime, self.flac_current_size = int(flac_stat.st_mtime), int(flac_stat.st_size) if os.path.exists(self.mp3_path): mp3_stat = os.stat(self.mp3_path) self.mp3_current_mtime, self.mp3_current_size = int(mp3_stat.st_mtime), int(mp3_stat.st_size) try: flac_tags = FLAC(self.flac_path) except flac_error: pass else: self.flac_artist = flac_tags.get('artist', [''])[0] self.flac_date = flac_tags.get('date', [''])[0] self.flac_album = flac_tags.get('album', [''])[0] self.flac_disc = flac_tags.get('discnumber', [''])[0] self.flac_track = flac_tags.get('tracknumber', [''])[0] self.flac_title = flac_tags.get('title', [''])[0] self.flac_has_lyrics = bool(flac_tags.get('unsyncedlyrics', [False])[0]) self.flac_has_picture = bool(flac_tags.pictures) if not os.path.exists(self.mp3_path): return try: mp3_tags = ID3(self.mp3_path) except id3_error: pass else: stored_metadata = json.loads(getattr(mp3_tags.get("COMM::'eng'"), 'text', ['{}'])[0]) self.flac_stored_mtime = stored_metadata.get('flac_mtime') self.flac_stored_size = stored_metadata.get('flac_size') self.mp3_stored_mtime = stored_metadata.get('mp3_mtime') self.mp3_stored_size = stored_metadata.get('mp3_size')
def check_flac_tags(flac_path): flac = FLAC(flac_path) if not flac.get('artist'): raise Exception(u'Missing artist tag on {0}'.format(flac_path)) if not flac.get('album'): raise Exception(u'Missing album tag on {0}'.format(flac_path)) if not flac.get('title'): raise Exception(u'Missing title tag on {0}'.format(flac_path)) track = flac.get('tracknumber') or flac.get('track') if type(track) in [str, unicode] and '/' in track: track = track.split('/') if type(track) is list: track = track[0] if not track: raise Exception(u'Missing track tag on {0}'.format(flac_path)) disc = flac.get('discnumber') or flac.get('disc') if type(disc) in [str, unicode] and '/' in disc: disc = disc.split('/') if type(disc) is list: disc = disc[0] if disc: return disc, track else: return track,
def __init__(self, path): super(FLACFile, self).__init__(path) self.extension = "flac" media = FLAC(path) self.bitrate = media.info.total_samples * media.info.bits_per_sample / media.info.length self.length = media.info.length self.metadata = { "artist": media.get( "artist", default=[None,] )[0], "album": media.get( "album", default=[None,] )[0], "title": media.get( "title", default=[None,] )[0], "genre": media.get( "genre", default=[None,] )[0], "trackno": self.parse_no( media.get("tracknumber", default=["",])[0] ), "trackof": self.parse_of( media.get("tracknumber", default=["",])[0] ), "diskno": self.parse_no( media.get("disknumber", default=["",])[0] ), "diskof": self.parse_of( media.get("disknumber", default=["",])[0] ), }
def update_flac(self, path: str, track: beatport.Track): f = FLAC(path) if UpdatableTags.title in self.config.update_tags and self.config.overwrite: f['TITLE'] = track.title if UpdatableTags.artist in self.config.update_tags and self.config.overwrite: f['ARTIST'] = self.config.artist_separator.join( [a.name for a in track.artists]) if UpdatableTags.album in self.config.update_tags and ( self.config.overwrite or f.get('ALBUM') == None): f['ALBUM'] = track.album.name if UpdatableTags.label in self.config.update_tags and ( self.config.overwrite or f.get('LABEL') == None): f['LABEL'] = track.label.name if UpdatableTags.bpm in self.config.update_tags and ( self.config.overwrite or f.get('BPM') == None): f['BPM'] = str(track.bpm) if UpdatableTags.genre in self.config.update_tags and ( self.config.overwrite or f.get('GENRE') == None): f['GENRE'] = ', '.join([g.name for g in track.genres]) if UpdatableTags.date in self.config.update_tags and ( self.config.overwrite or f.get('DATE') == None): f['DATE'] = track.release_date.strftime('%Y-%m-%d') #Year - part of date if UpdatableTags.key in self.config.update_tags and ( self.config.overwrite or f.get('INITIALKEY') == None): f['INITIALKEY'] = track.id3key() if UpdatableTags.publishdate in self.config.update_tags and ( self.config.overwrite or f.get('ORIGINALDATE') == None): f['ORIGINALDATE'] = str(track.publish_date.year) #Other tags if UpdatableTags.other in self.config.update_tags: f['WWWAUDIOFILE'] = track.url() f['WWWPUBLISHER'] = track.label.url('label') #Redownlaod cover if self.config.replace_art: try: url = track.art(self.config.art_resolution) r = requests.get(url) image = Picture() image.type = 3 image.mime = 'image/jpeg' image.desc = 'Cover' image.data = r.content f.clear_pictures() f.add_picture(image) except Exception: logging.warning('Error downloading cover for file: ' + path) f.save()
def setTags( self, tid, path ): t = FLAC( path ) if int( t.get('tidal_rip_version','0') ) < 1: d = self.getTags( tid ) for k in ['title','album','artist','albumartist', 'tracknumber','tracktotal','discnumber','disctotal', 'duration','albumduration', 'date','isrc','barcode','copyright','releasetype']: t[k] = str( d[k] ) for k in ['replaygain_track_gain','replaygain_track_peak']: t[k] = str( d[k] ) t['tidal_rip_version'] = '2' if 0: print('DICT', d) print(t.pprint()) print(t.tags) t.save()
def _get_tag(self): if self.suffix == '.flac': try: audio = FLAC(self.path) self.artist = audio['artist'][0] self.title = audio['title'][0] if audio.get('genre'): self.local_genres = audio['genre'][0] if audio.get('date'): self.local_year = audio['date'][0] if audio.pictures: self.cover_embedded = True except (FLACNoHeaderError, Exception) as e: pass if self.suffix == '.mp3': try: audio = EasyID3(self.path) self.artist = audio['artist'][0] self.title = audio['title'][0] if audio.get('genre'): self.local_genres = audio['genre'][0] if audio.get('date'): self.local_year = audio['date'][0] audio = MP3(self.path) for k in audio.keys(): if u'covr' in k or u'APIC' in k: self.cover_embedded = True except (HeaderNotFoundError, MutagenError, KeyError) as e: pass if self.suffix == '.m4a': try: audio = MP4(self.path) self.artist = audio['\xa9ART'][0] self.title = audio['\xa9nam'][0] if audio.get('\xa9gen'): self.local_genres = audio['\xa9gen'][0] if audio.get('\xa9day'): self.local_year = audio['\xa9day'][0] if audio.get('covr'): self.cover_embedded = True except (KeyError, MP4StreamInfoError, MutagenError) as e: pass
def convert_file(self, full_path): try: out_path = self.get_out_path(full_path) lame_options = self.lame_options or ['--preset', 'standard', '-h'] metadata = FLAC(full_path) try: os.makedirs(os.path.dirname(out_path)) except OSError as e: if e.errno != 17: raise # only raise if not "file exists" error flac_p = subprocess.Popen( [self.flac, '-s', '-d', '--stdout', full_path], stdout=subprocess.PIPE, preexec_fn=ignore_sigint) lame_cmd = [self.lame] + lame_options + ['--quiet', '-', out_path] lame_p = subprocess.Popen(lame_cmd, stdin=flac_p.stdout, preexec_fn=ignore_sigint) flac_p.wait() lame_p.wait() # now apply gain if self.apply_mp3gain: mp3gain_cmd = [self.mp3gain, '-q', '-T', '-r', '-k', out_path] subprocess.check_call(mp3gain_cmd, stdout=open('/dev/null', 'wb')) # finally, correct the tags id3data = File(out_path, easy=True) for attr in ('title', 'artist', 'album', 'date', 'genre', 'tracknumber'): id3data[attr] = metadata.get(attr) id3data.save() except Exception as e: status_queue.put(('ERROR', full_path, str(e))) if os.path.exists(out_path): os.unlink(out_path) else: status_queue.put(('OK', full_path, out_path))
def convert_file(self, full_path): try: out_path = self.get_out_path(full_path) lame_options = self.lame_options or ['--preset', 'standard', '-h'] metadata = FLAC(full_path) try: os.makedirs(os.path.dirname(out_path)) except OSError as e: if e.errno != 17: raise # only raise if not "file exists" error flac_p = subprocess.Popen( [self.flac, '-s', '-d', '--stdout', full_path], stdout=subprocess.PIPE, preexec_fn=ignore_sigint) lame_cmd = [self.lame] + lame_options + ['--quiet', '-', out_path] lame_p = subprocess.Popen(lame_cmd, stdin=flac_p.stdout, preexec_fn=ignore_sigint) flac_p.wait() lame_p.wait() # now apply gain if self.apply_mp3gain: mp3gain_cmd = [self.mp3gain, '-q', '-T', '-r', '-k', out_path] subprocess.check_call(mp3gain_cmd, stdout=open('/dev/null', 'wb')) # finally, correct the tags id3data = File(out_path, easy=True) for attr in ('title', 'artist', 'album', 'date', 'genre', 'tracknumber'): id3data[attr] = metadata.get(attr) id3data.save() except Exception as e: status_queue.put(('ERROR', full_path, str(e))) if os.path.exists(out_path): os.unlink(out_path) else: status_queue.put(('OK', full_path, out_path))
def __init__(self, path): super(FLACFile, self).__init__(path) self.extension = "flac" media = FLAC(path) self.bitrate = media.info.total_samples * media.info.bits_per_sample / media.info.length self.length = media.info.length self.metadata = { "artist": media.get("artist", default=[ None, ])[0], "album": media.get("album", default=[ None, ])[0], "title": media.get("title", default=[ None, ])[0], "genre": media.get("genre", default=[ None, ])[0], "trackno": self.parse_no(media.get("tracknumber", default=[ "", ])[0]), "trackof": self.parse_of(media.get("tracknumber", default=[ "", ])[0]), "diskno": self.parse_no(media.get("disknumber", default=[ "", ])[0]), "diskof": self.parse_of(media.get("disknumber", default=[ "", ])[0]), }
def read_flac(filename): try: audio = FLAC(filename) except FLACNoHeaderError: return {} tags = { 'filename' : filename, 'artist' : audio.get('artist'), 'album' : audio.get('album'), 'track' : audio.get('tracknumber') or audio.get('track'), 'title' : audio.get('title'), 'date' : audio.get('date') or audio.get('year'), } # Mutagen returns lists for each tag so we have to pull out the actual string for tag in tags: if tags[tag]: tags[tag] = tags[tag][0] tags['channels'] = audio.info.channels return __normalize_tags(tags)
def getAudioMetaData(service, ext): title = "" genre = "" artist = "" album = "" length = "" audio = None if fileExists("/tmp/.emcAudioTag.jpg"): os.remove("/tmp/.emcAudioTag.jpg") elif fileExists("/tmp/.emcAudioTag.png"): os.remove("/tmp/.emcAudioTag.png") elif fileExists("/tmp/.emcAudioTag.gif"): os.remove("/tmp/.emcAudioTag.gif") if service: path = service.getPath() if ext.lower() == ".mp3": try: audio = MP3(os.path.join(path), ID3 = EasyID3) except: audio = None elif ext.lower() == ".flac": try: audio = FLAC(os.path.join(path)) except: audio = None elif ext.lower() == ".ogg": try: audio = OggVorbis(os.path.join(path)) except: audio = None elif ext.lower() == ".mp4" or ext.lower() == ".m4a": try: audio = EasyMP4(os.path.join(path)) except: audio = None # first for older mutagen-package(under 1.27) # APEv2 is tagged from tools like "mp3tag" # no tagging in new mutagen.aac elif ext.lower() == ".aac": try: audio = APEv2File(os.path.join(path)) except: audio = None if audio: if ext.lower() != ".aac": length = str(datetime.timedelta(seconds=int(audio.info.length))) else: if isMutagenAAC: getlength = AAC(os.path.join(path)) length = str(datetime.timedelta(seconds=int(getlength.info.length))) else: length = str(datetime.timedelta(seconds=int(audio._Info.length))) title = audio.get('title', [service.getPath()])[0] try: genre = audio.get('genre', [''])[0] except: genre = "" artist = audio.get('artist', [''])[0] album = audio.get('album', [''])[0] # now we try to get embedded covers if ext.lower() == ".mp3": try: scover = ID3(service.getPath()) except: scover = None if scover: scovers = scover.getall("APIC") if len(scovers) > 0: try: ext = "." + scovers[0].mime.lower().split("/", -1)[1] writeTmpCover(scovers[0].data, ext) except Exception, e: emcDebugOut("[EMCMutagenSupport] Exception in Mp3EmbeddedCover: " + str(e)) elif ext.lower() == ".flac": try: scover = audio.pictures except: scover = None if scover: if scover[0].data: try: ext = "." + scover[0].mime.lower().split("/", -1)[1] writeTmpCover(scover[0].data, ext) except Exception, e: emcDebugOut("[EMCMutagenSupport] Exception in FlacEmbeddedCover: " + str(e)) elif ext.lower() == ".ogg": try: scover = audio except: scover = None if scover: for b64_data in scover.get("metadata_block_picture", []): try: data = base64.b64decode(b64_data) except (TypeError, ValueError): continue try: picture = Picture(data) except FLACError: continue try: ext = "." + picture.mime.lower().split("/", -1)[1] writeTmpCover(picture.data, ext) except Exception, e: emcDebugOut("[EMCMutagenSupport] Exception in OggEmbeddedCover: " + str(e))
def _process_library_uri(self): # first check if we deal with a track or an album if os.path.isfile(self.uri_in): logger.info('Processing {} as a library track.'.format(self.uri_in)) self.uri_out += 'track:' track = Music() # process mp3 and flac separately using the mutagen library if os.path.splitext(self.uri_in)[-1].lower() == '.mp3': track.filetype = 'mp3' self.uri_out += '/MP3{}'.format(self.uri_in.split('/MP3')[1]) mp = MP3(self.uri_in) track.track_title = mp.get('TIT2').text[0] track.album_title = mp.get('TALB').text[0] track.artist = mp.get('TPE1').text[0] self.music = track art = self._find_artwork(mp) if not art: logger.error('Could not find art for {}'.format(self.uri_in)) return False return True elif os.path.splitext(self.uri_in)[-1].lower() == '.flac': track.filetype = 'flac' self.uri_out += '/FLAC{}'.format(self.uri_in.split('/FLAC')[1]) fl = FLAC(self.uri_in) track.track_title = fl.get('title')[0] track.album_title = fl.get('album')[0] track.artist = fl.get('artist')[0] self.music = track art = self._find_artwork(fl) if not art: logger.error('Could not find art for {}'.format(self.uri_in)) return False return True else: logger.error('File type {} not implemented'.format(os.path.splitext(self.uri_in)[-1])) return False elif os.path.isdir(self.uri_in): # if a folder is given: assume it is an album folder containing tracks logger.info('Processing {} as a library album.'.format(self.uri_in)) self.uri_out += 'album:' album = Music() if 'MP3' in self.uri_in: self.uri_out += '/MP3{}'.format(self.uri_in.split('/MP3')[1]) tracks = self._list_files(self.uri_in, 'mp3') if tracks: album.filetype = 'mp3' mp = MP3(tracks[0]) album.album_title = mp.get('TALB').text[0] album.artist = mp.get('TPE1').text[0] self.music = album found_art = self._find_artwork(mp) if not found_art: logger.error('Could not find art for {}'.format(self.uri_in)) return False return True elif 'FLAC' in self.uri_in: self.uri_out += '/FLAC{}'.format(self.uri_in.split('/FLAC')[1]) tracks = self._list_files(self.uri_in, 'flac') if tracks: album.filetype = 'flac' fl = FLAC(tracks[0]) album.album_title = fl.get('album')[0] album.artist = fl.get('artist')[0] self.music = album found_art = self._find_artwork(fl) if not found_art: logger.error('Could not find art for {}'.format(self.uri_in)) return False return True else: logger.error('No files found in album folder {}.'.format(self.uri_in)) return False else: logger.error('no valid library uri presented: {}'.format(self.uri_in)) return False
def getSongTags(file): # Get the actual ID3 tags for music songs as the server is lacking that info rating = 0 comment = "" hasEmbeddedCover = False isTemp,filename = getRealFileName(file) log.info( "getting song ID3 tags for " + filename) try: ###### FLAC FILES ############# if filename.lower().endswith(".flac"): audio = FLAC(filename) if audio.get("comment"): comment = audio.get("comment")[0] for pic in audio.pictures: if pic.type == 3 and pic.data: #the file has an embedded cover hasEmbeddedCover = True break if audio.get("rating"): rating = float(audio.get("rating")[0]) #flac rating is 0-100 and needs to be converted to 0-5 range if rating > 5: rating = (rating / 100) * 5 ###### MP3 FILES ############# elif filename.lower().endswith(".mp3"): audio = ID3(filename) if audio.get("APIC:Front Cover"): if audio.get("APIC:Front Cover").data: hasEmbeddedCover = True if audio.get("comment"): comment = audio.get("comment")[0] if audio.get("POPM:Windows Media Player 9 Series"): if audio.get("POPM:Windows Media Player 9 Series").rating: rating = float(audio.get("POPM:Windows Media Player 9 Series").rating) #POPM rating is 0-255 and needs to be converted to 0-5 range if rating > 5: rating = (rating / 255) * 5 else: log.info( "Not supported fileformat or unable to access file: %s" %(filename)) #the rating must be a round value rating = int(round(rating,0)) except Exception as e: #file in use ? log.error("Exception in getSongTags %s" % e) rating = None #remove tempfile if needed.... if isTemp: xbmcvfs.delete(filename) return (rating, comment, hasEmbeddedCover)
def getSongTags(file): # Get the actual ID3 tags for music songs as the server is lacking that info rating = 0 comment = "" hasEmbeddedCover = False isTemp,filename = getRealFileName(file) log.info( "getting song ID3 tags for " + filename) try: ###### FLAC FILES ############# if filename.lower().endswith(".flac"): audio = FLAC(filename) if audio.get("comment"): comment = audio.get("comment")[0] for pic in audio.pictures: if pic.type == 3 and pic.data: #the file has an embedded cover hasEmbeddedCover = True break if audio.get("rating"): rating = float(audio.get("rating")[0]) #flac rating is 0-100 and needs to be converted to 0-5 range if rating > 5: rating = (rating / 100) * 5 ###### MP3 FILES ############# elif filename.lower().endswith(".mp3"): audio = ID3(filename) if audio.get("APIC:Front Cover"): if audio.get("APIC:Front Cover").data: hasEmbeddedCover = True if audio.get("comment"): comment = audio.get("comment")[0] if audio.get("POPM:Windows Media Player 9 Series"): if audio.get("POPM:Windows Media Player 9 Series").rating: rating = float(audio.get("POPM:Windows Media Player 9 Series").rating) #POPM rating is 0-255 and needs to be converted to 0-5 range if rating > 5: rating = (rating / 255) * 5 else: log.info( "Not supported fileformat or unable to access file: %s" %(filename)) #the rating must be a round value rating = int(round(rating,0)) except Exception as e: #file in use ? log.error("Exception in getSongTags %s" % e) rating = None #remove tempfile if needed.... if isTemp: xbmcvfs.delete(filename) return (rating, comment, hasEmbeddedCover)
if filename.endswith('.mp3'): Easy3 = EMP3(filename) tag = TinyTag.get(filename) mbztrackids = Easy3["musicbrainz_trackid"][0] title = Easy3["title"][0] tpos = tag.track duration = tag.duration duration = math.ceil(duration) duration = time.strftime("%M:%S", time.gmtime(duration)) mbztrackid.append(mbztrackids) tracknames.append(title) trackpositions.append(tpos) trackdurations.append(duration) elif filename.endswith('.flac'): flac = FLAC(filename) mbztrackids = flac.get("musicbrainz_trackid")[0] title = flac.get("title")[0] tpos = flac.get("tracknumber")[0] duration = flac.info.length duration = math.ceil(duration) duration = time.strftime("%M:%S", time.gmtime(duration)) mbztrackid.append(mbztrackids) tracknames.append(title) trackpositions.append(tpos) trackdurations.append(duration) if filename.endswith('.mp3'): amp3 = MP3(filename) easyMP3 = EMP3(filename) comment = amp3.get("COMM::eng") label = amp3.get("TPUB")
print('It is also only for Albums in flac format') print('If path is network location please use UNC path \\\servername\\\path') path = input("Enter Location of Album: ") tracknames = [] trackpositions = [] trackdurations = [] mbztrackid = [] compilation = 'false' template = 'album.nfo' for name in os.listdir(path): if name.lower().endswith(".flac"): filename = os.path.join(path, name) audio = FLAC(filename) title = audio.get("title")[0] tracknumber = audio.get("tracknumber")[0] mbztrackids = audio.get("musicbrainz_trackid")[0] duration = audio.info.length duration = math.ceil(duration) duration = str(datetime.timedelta(seconds=duration)) tracknames.append(title) mbztrackid.append(mbztrackids) trackpositions.append(tracknumber) trackdurations.append(duration) comment = audio.get("comment")[0] album = audio.get("album")[0] artist = audio.get("artist")[0] genre = audio.get("genre")[0] year = audio.get("originalyear")[0]