本文整理汇总了Python中mutagen.flac.FLAC.has_key方法的典型用法代码示例。如果您正苦于以下问题:Python FLAC.has_key方法的具体用法?Python FLAC.has_key怎么用?Python FLAC.has_key使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mutagen.flac.FLAC
的用法示例。
在下文中一共展示了FLAC.has_key方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: CopyTags
# 需要导入模块: from mutagen.flac import FLAC [as 别名]
# 或者: from mutagen.flac.FLAC import has_key [as 别名]
def CopyTags(source_file, target_file):
f = FLAC(source_file)
m = EasyID3(target_file)
for key in ['artist', 'title', 'album', 'date', 'genre', 'tracknumber']:
if f.has_key(key):
m[key] = f[key]
m.save()
if f.has_key('discnumber'):
m = MP3(target_file)
m['TPOS'] = TPOS(encoding=3, text=f['discnumber'])
m.save()
示例2: getsubmission
# 需要导入模块: from mutagen.flac import FLAC [as 别名]
# 或者: from mutagen.flac.FLAC import has_key [as 别名]
def getsubmission(tfile):
data = open(tfile).read()
torrent = decode(data)
tname = torrent['info']['name']
for file in torrent["info"]["files"]:
name = "/".join(file["path"])
flac_re = re.compile(".flac")
if flac_re.search(name) != None:
flacname=name
log_re = re.compile(".log")
if log_re.search(name) !=None:
logname=name
fpath = os.path.join(tname,flacname)
lpath = os.path.join(tname,logname)
audio = FLAC(fpath)
print audio.keys()
if not audio.has_key('musicbrainz_albumid'):
print "ReleaseID tag is not set. Has this flac been tagged by picard?"
return(-1)
albumid = audio['musicbrainz_albumid'][0]
print albumid
q = ws.Query()
try:
inc = ws.ReleaseIncludes(artist=True, releaseEvents=True, labels=True,
discs=True, tracks=True)
release = q.getReleaseById(albumid, inc)
except ws.WebServiceError, e:
print 'Error:', e
return(-1)
示例3: getFlacLyrics
# 需要导入模块: from mutagen.flac import FLAC [as 别名]
# 或者: from mutagen.flac.FLAC import has_key [as 别名]
def getFlacLyrics(filename, getlrc):
try:
tags = FLAC(filename)
if tags.has_key('lyrics'):
lyr = tags['lyrics'][0]
match1 = re.compile('\[(\d+):(\d\d)(\.\d+|)\]').search(lyr)
if (getlrc and match1) or ((not getlrc) and (not match1)):
return lyr
except:
return None
示例4: dir_flac_mbid
# 需要导入模块: from mutagen.flac import FLAC [as 别名]
# 或者: from mutagen.flac.FLAC import has_key [as 别名]
def dir_flac_mbid(dir):
if not os.path.isdir(dir):
print "Directory does not exist"
return -1
for root, dirs, files in os.walk(dir):
for f in files:
ext_re = re.compile(".*\.flac")
if re.search(ext_re, f):
path = os.path.join(root, f)
flac = FLAC(path)
if flac.has_key("musicbrainz_albumid"):
return flac["musicbrainz_albumid"][0]
return -1
示例5: fixMetadata
# 需要导入模块: from mutagen.flac import FLAC [as 别名]
# 或者: from mutagen.flac.FLAC import has_key [as 别名]
def fixMetadata(files):
for path,track in files:
try:
metadata = FLAC(path) # metadata pulled from .flac
except (FLACNoHeaderError):
# Lack of proper FLAC header is not necessarily a bad FLAC
metadata = {}
if isSong(track):
if metadata.has_key('tracknumber'):
setTrackNumber(track, metadata['tracknumber'][0])
else:
deleteTrack(track)
raise ItunesFormatError(filename + " is not a FLAC file.")
示例6: dir_flac_year
# 需要导入模块: from mutagen.flac import FLAC [as 别名]
# 或者: from mutagen.flac.FLAC import has_key [as 别名]
def dir_flac_year(dir):
if not os.path.isdir(dir):
print "Directory does not exist"
return -1
for f in os.listdir(dir):
ext_re = re.compile(".*\.flac")
if re.search(ext_re, f):
path = os.path.join(dir, f)
flac = FLAC(path)
if flac.has_key("date"):
year_re = re.compile("[0-9]{4}")
date = flac["date"][0]
year = (re.search(year_re, date)).group()
return year
return -1
示例7: saveTags
# 需要导入模块: from mutagen.flac import FLAC [as 别名]
# 或者: from mutagen.flac.FLAC import has_key [as 别名]
def saveTags(self):
print('Tags saving.\n')
if search("flac$", splitext(self._basename)[1], I):
try:
track = FLAC(join(self._dirname, self._basename))
except:
print('No FLAC tag found\n')
elif search("ape$", splitext(self._basename)[1], I):
try:
track = APEv2(join(self._dirname, self._basename))
except:
print ('No APE tag found\n')
elif search("wv$", splitext(self._basename)[1], I):
try:
track = WavPack(join(self._dirname, self._basename))
except:
print ('No WV tag found\n')
else:
return
try:
if track.has_key('genre'):
self._genre = " ".join(track['genre'])
print('Genre : ' + " ".join(track['genre']))
if track.has_key('date') or track.has_key('year'):
if track.has_key('date'):
year = 'date'
else:
year = 'year'
self._date = " ".join(track[year])
print('Year : ' + " ".join(track[year]))
if track.has_key('artist'):
self._artist = " ".join(track['artist'])
print('Artist : ' + " ".join(track['artist']))
if track.has_key('album'):
self._album = " ".join(track['album'])
print('Album : ' + " ".join(track['album']))
print('\n')
except:
track = {}
示例8:
# 需要导入模块: from mutagen.flac import FLAC [as 别名]
# 或者: from mutagen.flac.FLAC import has_key [as 别名]
mp3.save()
# Get the picture tag from the flac file and store it
# in the flac dir and the mp3 dir and the mp3 file.
pictures = flacTags.pictures
noOfPictures = 0
for pic in pictures:
noOfPictures = noOfPictures + 1
#Save pic to file in source dir and in dest dir.
imgext = '.img'
if (pic.mime == "image/jpeg") or (frame.mime == "image/jpg"): imgext = '.jpg'
if (pic.mime == "image/png") : imgext = '.png'
if (pic.mime == "image/gif") : imgext = '.gif'
if noOfPictures == 1:
if flacTags.has_key('albumartist'):
albumArtist = flacTags['albumartist'][0]
elif flacTags.has_key('album artist'):
albumArtist = flacTags['album artist'][0]
elif flacTags.has_key('artist'):
albumArtist = flacTags['artist'][0]
else:
albumArtist = ""
if flacTags.has_key('album'):
album = flacTags['album'][0]
else:
album = ""
if albumArtist == "" and album == "":
albumArtName = "art_" + noOfPictures
示例9: copyFLAC
# 需要导入模块: from mutagen.flac import FLAC [as 别名]
# 或者: from mutagen.flac.FLAC import has_key [as 别名]
def copyFLAC(flacFile, mpgFile):
from mutagen.flac import FLAC, Picture
from mutagen.mp3 import MP3
from mutagen.id3 import ID3
bChange = False
# audioMP3 = MP3('smiley.mp3', ID3=EasyID3)
audioMP3 = MP3()
audioMP3.add_tags(ID3=CompatID3)
bNew = True
audioFLAC = FLAC(flacFile)
if audioFLAC.has_key('tracktotal'):
tracktotal = audioFLAC["tracktotal"][0]
else:
tracktotal = 0
if not audioFLAC.has_key('albumartist'):
audioFLAC["albumartist"] = audioFLAC["artist"]
if not audioFLAC.has_key('compilation'):
audioFLAC["compilation"] = 0
print "--FLAC--------------------------------------------"
for tag in audioFLAC.keys():
# print >> sys.stdout, "--> verarbeite Key: ", tag
# if 'APIC' in tag:
# print 'Tag {0}'.format(tag)
# else:
# print >> sys.stdout, "--> verarbeite Key: Tag {0}: {1}".format(tag, textTag.encode('UTF-8'))
if tag == "tracktotal": pass
else:
# id3.add(mutagen.id3.COMM(encoding=3,text=relationshipLink, lang="eng", desc="MusicGrabberSig"))
# Tag COMM:Kommentar:'DEU': von Vinyl
if tag == "tracknumber":
audioFLAC[tag]='{0}/{1}'.format(audioFLAC[tag][0], tracktotal)
# audioFLAC[tag]='{0}/{1}'.format(audioFLAC[tag], tracktotal)
searchTag = tag
if "comment" in tag: searchTag = 'COMMENTS'
if "description" in tag: searchTag = 'COMMENTS'
# if not str.upper(tag) in id3Trans.flacFrames:
if not hasFrame(searchTag):
if "replaygain" in tag: continue
print >> sys.stderr, "Key nicht gefunden: ", tag
continue
id3Frame = getFrame(searchTag)
# audioMP3[id3Frame] = audioFLAC[tag]
# for textTag in audioFLAC[tag]:
# print >> sys.stderr, "tag: %s frame: %s " % (tag, id3Frame.__name__)
if "comment" in tag:
# audioMP3.add(id3Frame(encoding=3, text= audioFLAC[tag], lang="DEU", desc="Kommentar"))
try: audioMP3[id3Frame.__name__] = id3Frame(3, text=audioFLAC[tag], lang="DEU", desc="Kommentar")
except: pass
else:
audioMP3[id3Frame.__name__] = id3Frame(3, text=audioFLAC[tag])
# audioMP3.add(id3Frame(encoding=3, text= audioFLAC[tag]))
bChange = True
# print u'Tag {0}: {1} --> MP3 zugefuegt'.format(id3Frame, audioFLAC[tag])
if bChange == True:
# print dir(audioMP3)
# if bNew : audioMP3.save(mpgFile,v1=2)
# else : audioMP3.save(v1=2)
audioMP3.tags.update_to_v23()
if bNew : audioMP3.tags.save(filename=mpgFile, v2=3)
else : audioMP3.tags.save(v2=3)
print '-'*40
示例10: renameAll
# 需要导入模块: from mutagen.flac import FLAC [as 别名]
# 或者: from mutagen.flac.FLAC import has_key [as 别名]
def renameAll(self):
print('Files renaming if possible.\n')
filelist = []
for i in listdir(self._dirname):
if getsize(join(self._dirname, i)) / 1048576 < 150 and splitext(i)[1] in extensions:
filelist.append(i)
filelist.sort()
for i in filelist:
if search("tta$", splitext(i)[1], I) or search("shn$", splitext(i)[1], I) or search("wav$", splitext(i)[1], I):
typeT = 3
elif search("flac$", splitext(i)[1], I):
try:
track = FLAC(join(self._dirname, i))
except:
track = {}
typeT = 0
elif search("mp3$", splitext(i)[1], I):
try:
track = MP3(join(self._dirname, i))
except:
track = {}
typeT = 1
else:
if search("wv$", splitext(i)[1], I):
try:
track = WavPack(join(self._dirname, i))
except:
track = {}
elif search("ape$", splitext(i)[1], I):
try:
track = APEv2(join(self._dirname, i))
except:
track = {}
typeT = 2
if typeT != 3 and ( track.has_key('tracknumber') or track.has_key('track') ):
if track.has_key('tracknumber'):
numT = track['tracknumber'][0].split("/")[0]
else:
numT = track['track'][0]
if len(numT) < 2:
numT = '0' + numT
if track.has_key('tracknumber'):
track['tracknumber'] = numT
else:
track['track'] = numT
track.save()
elif search("^\d\d", splitext(i)[0]):
numT = splitext(i)[0][:2]
elif search("^\d", splitext(i)[0]):
numT = "0" + splitext(i)[0][:2]
if typeT != 3 and track.has_key('title'):
titleT = " - ".join(track['title'])
if search("/", titleT):
titleT = sub("/", " - ", sub("\s/\s", " - ", " - ".join(track['title'])))
if search("^track\d\d$", splitext(basename(i))[0]):
track['title'] = titleT
track.save()
else:
titleT = strip(lstrip(lstrip(lstrip(splitext(i)[0], "0123456789")), ".-_"))
if search("`", titleT):
titleT = sub("`", "'", titleT)
print('Renaming File : ' + i)
print(' => ' + numT[:2] + "-" + titleT + splitext(i)[1])
move(join(self._dirname, i), join(self._dirname, numT[:2] + "-" + titleT + splitext(i)[1]))
print('\n')
示例11: artist_to_genre
# 需要导入模块: from mutagen.flac import FLAC [as 别名]
# 或者: from mutagen.flac.FLAC import has_key [as 别名]
print 'ERROR: Vorbis comment has no "artist" key in file %s' % os.path.join(root, name)
continue
artist = audio['artist']
genre = artist_to_genre(artist[0])
if genre != None:
audio["genre"] = genre
audio_set = True
elif name.lower().endswith(".flac"):
try:
audio = FLAC(os.path.join(root, name))
except Exception, e:
print 'ERROR: Flac Comment Error %s : %s' % (e, os.path.join(root, name))
continue
if not audio.has_key('artist'):
print 'ERROR: Vorbis comment has no "artist" key in file %s' % os.path.join(root, name)
continue
artist = audio['artist']
genre = artist_to_genre(artist[0])
if genre != None:
audio["genre"] = genre
audio_set = True
if audio_set:
try:
tag_count += 1
print "* %d %s %s" % (tag_count, genre, os.path.join(root, name))
# what shall we do with the file?
if run_mode == RUN_MODE_NORMAL:
#print "saving file %s" % (name)
示例12: update
# 需要导入模块: from mutagen.flac import FLAC [as 别名]
# 或者: from mutagen.flac.FLAC import has_key [as 别名]
def update(self, metadata, media, lang):
# Set title if needed.
if media and metadata.title is None: metadata.title = media.title
valid_posters = []
for t in media.tracks:
for i in media.tracks[t].items:
for p in i.parts:
filename = unicodize(p.file)
path = os.path.dirname(filename)
(fileroot, fext) = os.path.splitext(filename)
pathFiles = {}
for pth in os.listdir(path):
pathFiles[pth.lower()] = pth
# Add the filename as a base, and the dirname as a base for poster lookups
passFiles = {}
passFiles['posters'] = artFiles['posters'] + [fileroot, SplitPath(path)[-1]]
# Look for posters
for e in artExt:
for a in passFiles['posters']:
f = (a + '.' + e).lower()
if f in pathFiles.keys():
data = Core.storage.load(os.path.join(path, pathFiles[f]))
posterName = hashlib.md5(data).hexdigest()
valid_posters.append(posterName)
if posterName not in metadata.posters:
metadata.posters[posterName] = Proxy.Media(data)
Log('Local asset image added: ' + f + ', for file: ' + filename)
else:
Log('skipping add for local art')
# Look for embedded id3 APIC images in mp3 files
if fext.lower() == '.mp3':
try: f = ID3(filename)
except:
Log('Bad ID3 tags. Skipping.')
continue
#available_at date from TDRC
try:
metadata.originally_available_at = Datetime.ParseDate('01-01-' + f.getall("TDRC")[0].text[0].get_text()).date()
except:
pass
#Genres from TCON
try:
genres = f.getall('TCON')
metadata.genres.clear()
for g in genres:
metadata.genres.add(g)
except:
pass
for frame in f.getall("APIC"):
if (frame.mime == 'image/jpeg') or (frame.mime == 'image/jpg'): ext = 'jpg'
elif frame.mime == 'image/png': ext = 'png'
elif frame.mime == 'image/gif': ext = 'gif'
else: ext = ''
posterName = hashlib.md5(frame.data).hexdigest()
valid_posters.append(posterName)
if posterName not in metadata.posters:
Log('Adding embedded APIC art from mp3 file: ' + filename)
metadata.posters[posterName] = Proxy.Media(frame.data, ext=ext)
else:
Log('skipping already added APIC')
# Look for coverart atoms in mp4/m4a
elif fext.lower() in ['.mp4','.m4a','.m4p']:
try: mp4fileTags = MP4(filename)
except:
Log('Bad mp4 tags. Skipping.')
continue
try:
data = str(mp4fileTags["covr"][0])
posterName = hashlib.md5(data).hexdigest()
valid_posters.append(posterName)
if posterName not in metadata.posters:
metadata.posters[posterName] = Proxy.Media(data)
Log('Adding embedded coverart from m4a/mp4 file: ' + filename)
except: pass
# Look for coverart atoms in flac files
elif fext.lower() == '.flac':
try: f = FLAC(filename)
except:
Log('Bad FLAC tags. Skipping.')
continue
for p in f.pictures:
posterName = hashlib.md5(p.data).hexdigest()
valid_posters.append(posterName)
if posterName not in metadata.posters:
Log('Adding embedded art from FLAC file: ' + filename)
metadata.posters[posterName] = Proxy.Media(p.data)
else:
Log('skipping already added FLAC art')
# Look for coverart atoms in ogg files
elif fext.lower() == '.ogg':
try:
f = OggVorbis(filename)
if f.has_key('metadata_block_picture'):
for pic in f['metadata_block_picture']:
p = Picture(base64.standard_b64decode(pic))
if (p.mime == 'image/jpeg') or (p.mime == 'image/jpg'): ext = 'jpg'
elif p.mime == 'image/png': ext = 'png'
elif p.mime == 'image/gif': ext = 'gif'
else: ext = ''
#.........这里部分代码省略.........