本文整理汇总了Python中CDDB.read方法的典型用法代码示例。如果您正苦于以下问题:Python CDDB.read方法的具体用法?Python CDDB.read怎么用?Python CDDB.read使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类CDDB
的用法示例。
在下文中一共展示了CDDB.read方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: query
# 需要导入模块: import CDDB [as 别名]
# 或者: from CDDB import read [as 别名]
def query(category, discid, xcode='utf8:utf8'):
#from quodlibet's cddb plugin by Michael Urman
discinfo = {}
tracktitles = {}
read, info = CDDB.read(category, discid, **CLIENTINFO)
if read != 210: return None
xf, xt = xcode.split(':')
for key, value in info.iteritems():
try: value = value.decode('utf-8', 'replace').strip().encode(
xf, 'replace').decode(xt, 'replace')
except AttributeError: pass
if key.startswith('TTITLE'):
try: tracktitles[int(key[6:])] = value
except ValueError: pass
elif key == 'DGENRE': discinfo['genre'] = value
elif key == 'DTITLE':
dtitle = value.strip().split(' / ', 1)
if len(dtitle) == 2:
discinfo['artist'], discinfo['title'] = dtitle
else: discinfo['title'] = dtitle[0].strip()
elif key == 'DYEAR': discinfo['year'] = value
return discinfo, tracktitles
示例2: cddbRequest
# 需要导入模块: import CDDB [as 别名]
# 或者: from CDDB import read [as 别名]
def cddbRequest(self, discInfo):
""" Return disc information from online CDDB, None if request fails """
import CDDB, socket
# Make sure to not be blocked by the request
socket.setdefaulttimeout(consts.socketTimeout)
try:
(status, info) = CDDB.query(discInfo)
if status == 200:
disc = info # Success
elif status == 210:
disc = info[0] # Exact multiple matches
elif status == 211:
disc = info[0] # Inexact multiple matches
else:
raise Exception, "Unknown disc (phase 1 returned %u)" % status
(status, info) = CDDB.read(disc["category"], disc["disc_id"])
if status == 210:
return info
else:
raise Exception, "Unknown disc (phase 2 returned %u)" % status
except:
logger.error("[%s] CDDB request failed\n\n%s" % (MOD_INFO[modules.MODINFO_NAME], traceback.format_exc()))
return None
示例3: get_cddb
# 需要导入模块: import CDDB [as 别名]
# 或者: from CDDB import read [as 别名]
def get_cddb(self):
try:
import CDDB, DiscID
except ImportError:
fatal('You need python-cddb (http://cddb-py.sf.net) to convert cds. Please install it.')
disc_id = DiscID.disc_id(DiscID.open(self.dev))
query_info = CDDB.query(disc_id)[1]
if not query_info:
fatal('The disk is not listed in FreeDB, dir2ogg only supports disk listed in MusicBrainz or FreeDB')
if isinstance(query_info, list):
query_info = query_info[0]
read_info = CDDB.read(query_info['category'], query_info['disc_id'])[1]
for track in range(disc_id[1]):
title = {}
title['discid'] = query_info['disc_id']
title['artist'], title['album'] = (track.strip() for track in query_info['title'].split("/"))
title['genre'] = read_info['DGENRE']
title['date'] = read_info['DYEAR']
title['title'] = read_info['TTITLE' + str(track)]
title['tracktotal'] = str(len(range(disc_id[1])) + 1)
title['ntracknumber'] = '0' * (len(title['tracktotal'] ) - len(str(track+1)) ) + str(track+1)
title['tracknumber'] = str(track+1)
for key, val in title.items():
title[key] = unicode(str(val), "ISO-8859-1")
ConvertTrack(self.dev, self.conf, track+1, title)
示例4: get_cddb_info
# 需要导入模块: import CDDB [as 别名]
# 或者: from CDDB import read [as 别名]
def get_cddb_info(self):
try:
disc = DiscID.open(self.device)
self.info = DiscID.disc_id(disc)
status, info = CDDB.query(self.info)
except IOError:
return
if status in (210, 211):
info = info[0]
status = 200
if status != 200:
return
(status, info) = CDDB.read(info['category'], info['disc_id'])
title = info['DTITLE'].split(" / ")
for i in range(self.info[1]):
tr = self[i]
tr.set_tag_raw('title',
info['TTITLE' + `i`].decode('iso-8859-15', 'replace'))
tr.set_tag_raw('album',
title[1].decode('iso-8859-15', 'replace'))
tr.set_tag_raw('artist',
title[0].decode('iso-8859-15', 'replace'))
tr.set_tag_raw('year',
info['EXTD'].replace("YEAR: ", ""))
tr.set_tag_raw('genre',
info['DGENRE'])
self.name = title[1].decode('iso-8859-15', 'replace')
event.log_event('cddb_info_retrieved', self, True)
示例5: get_cddb_info
# 需要导入模块: import CDDB [as 别名]
# 或者: from CDDB import read [as 别名]
def get_cddb_info(self):
try:
disc = DiscID.open(self.device)
self.info = DiscID.disc_id(disc)
status, info = CDDB.query(self.info)
except IOError:
return
if status in (210, 211):
info = info[0]
status = 200
if status != 200:
return
(status, info) = CDDB.read(info["category"], info["disc_id"])
title = info["DTITLE"].split(" / ")
for i in range(self.info[1]):
tr = self[i]
tr.set_tag_raw("title", info["TTITLE" + str(i)].decode("iso-8859-15", "replace"))
tr.set_tag_raw("album", title[1].decode("iso-8859-15", "replace"))
tr.set_tag_raw("artist", title[0].decode("iso-8859-15", "replace"))
tr.set_tag_raw("year", info["EXTD"].replace("YEAR: ", ""))
tr.set_tag_raw("genre", info["DGENRE"])
self.name = title[1].decode("iso-8859-15", "replace")
event.log_event("cddb_info_retrieved", self, True)
示例6: get_CDDB_tag
# 需要导入模块: import CDDB [as 别名]
# 或者: from CDDB import read [as 别名]
def get_CDDB_tag(self, query_status, query_info):
if self.is_audio_cd:
read_status, read_info = CDDB.read(query_info['category'], query_info['disc_id'])
print "read status: ", read_status
print "read info: ", read_info
else:
return
self.song_list = []
if query_status in [200, 210]:
self.is_audio_cd = True
self.cddb_disc_id_b10 = self.disc_id[0]
self.cddb_disc_id_b16 = query_info['disc_id']
self.total_tracks = self.disc_id[1]
if read_status == 210:
for i in range(self.disc_id[1]):
n = "%.02d" %(i + 1)
title = "%s" %(read_info['TTITLE' + `i`])
frame = self.disc_id[i+2]
self.song_list.append({"track_number":int(n), "title":title, "num_frame":frame})
print "Song_list: ", self.song_list
if read_info['DTITLE']:
disc_title = read_info['DTITLE']
else:
disc_title = query_info[0]['title']
self.artist, self.album = re.split(" / ", disc_title)
if "," in self.artist:
a, b = re.split(", ", self.artist)
self.artist = b.title() + " " + a.title()
try:
self.disc_len = read_info['disc_len']
except:
self.disc_len = self.disc_id[2+self.disc_id[1]]
self.year = read_info['DYEAR']
if read_info['DGENRE']:
self.cddb_genre = read_info['DGENRE']
else:
self.cddb_genre = query_info[0]['category']
elif read_status in [401, 402, 403, 409, 417]:
self.error = read_status
else:
return
elif query_status in [211, 202, 403, 409]:
self.error = query_status
try:
cdaudio.close()
except:
pass
return self.error
else:
cdaudio.close()
return
示例7: query
# 需要导入模块: import CDDB [as 别名]
# 或者: from CDDB import read [as 别名]
def query(category, discid, xcode='utf8:utf8'):
discinfo = {}
tracktitles = {}
dump = path.join(path.expanduser("~"), '.cddb', category, discid)
try:
for line in file(dump):
if line.startswith("TTITLE"):
track, title = line.split("=", 1)
try: track = int(track[6:])
except (ValueError): pass
else: tracktitles[track] = \
title.decode('utf-8', 'replace').strip()
elif line.startswith("DGENRE"):
discinfo['genre'] = line.split('=', 1)[1].strip()
elif line.startswith("DTITLE"):
dtitle = line.split('=', 1)[1].strip().split(' / ', 1)
if len(dtitle) == 2:
discinfo['artist'], discinfo['title'] = dtitle
else:
discinfo['title'] = dtitle[0].strip()
elif line.startswith("DYEAR"):
discinfo['year'] = line.split('=', 1)[1].strip()
except EnvironmentError: pass
else: return discinfo, tracktitles
read, info = CDDB.read(category, discid, **CLIENTINFO)
if read != 210: return None
try: os.makedirs(path.join(path.expanduser("~"), '.cddb'))
except EnvironmentError: pass
try:
save = file(dump, 'w')
keys = info.keys()
keys.sort()
for key in keys:
print>>save, "%s=%s" % (key, info[key])
save.close()
except EnvironmentError: pass
xf, xt = xcode.split(':')
for key, value in info.iteritems():
try: value = value.decode('utf-8', 'replace').strip().encode(
xf, 'replace').decode(xt, 'replace')
except AttributeError: pass
if key.startswith('TTITLE'):
try: tracktitles[int(key[6:])] = value
except ValueError: pass
elif key == 'DGENRE': discinfo['genre'] = value
elif key == 'DTITLE':
dtitle = value.strip().split(' / ', 1)
if len(dtitle) == 2:
discinfo['artist'], discinfo['title'] = dtitle
else: discinfo['title'] = dtitle[0].strip()
elif key == 'DYEAR': discinfo['year'] = value
return discinfo, tracktitles
示例8: set_category
# 需要导入模块: import CDDB [as 别名]
# 或者: from CDDB import read [as 别名]
def set_category(self, cat):
self._clear_md()
cache_path = os.path.join(self.cache_dir, '{0}-{1}'.format(self.fingerprint, cat))
for k,v in cached(lambda:CDDB.read(cat, self.fingerprint)[1])(cache_path).items():
if not v or k[0] not in 'DTE':
continue
elif k == 'DTITLE':
self.metadata[0]['artist'],_,self.metadata[0]['title'] = v.partition(' / ')
elif k == 'DGENRE': self.metadata[0]['genre'] = v
elif k == 'DYEAR': self.metadata[0]['year'] = v
elif k.startswith('TTITLE'): self.metadata[int(k[6:])+1]['title'] = v
示例9: query
# 需要导入模块: import CDDB [as 别名]
# 或者: from CDDB import read [as 别名]
def query(self):
def fixchars(pathname):
"""Fixes characters that cause escaping problems in string
constructions used to execute commands on the OS or in the DB"""
pathname = pathname.replace(os.sep, "-")
pathname = pathname.replace("\"", "")
pathname = pathname.replace("?", "")
return pathname
def padNum(num):
if int(num) < 10:
return "0" + str(num)
else:
return str(num)
delims = ("/", " - ")
def findTitle(title, count):
"""Tries the delimiters in order until it finds the right one"""
#print title
#print len(delims)
if count < len(delims):
titleparts = title.split(delims[count])
#print titleparts
if len(titleparts) == 2:
self.artistName = fixchars(titleparts[0].strip())
self.albumName = fixchars(titleparts[1].strip())
return True
else:
return findTitle(title, count+1)
return False
self.category = fixchars(self.query_info["category"])
self.disc_id = self.query_info["disc_id"]
self.title = fixchars(self.query_info["title"])
if not findTitle(self.title, 0):
raise "Title not parsed: %s" % self.title
(track_status, track_info) = CDDB.read(self.category, self.disc_id)
self.genre = fixchars(track_info['DGENRE'])
self.year = track_info['DYEAR']
if track_info.has_key('disc_len'):
self.albumlength = str(float(track_info['disc_len']) / 60) + " min."
else:
self.albumlength = ""
self.comments = fixchars(track_info['EXTD'])
self.albumtitle = fixchars(track_info['DTITLE'])
for (tracknum,trackname) in track_info.items():
if tracknum.find("TTITLE") != -1:
num = int(tracknum[len("TTITLE"):]) + 1
self.tracks[padNum(num)] = fixchars(trackname)
示例10: _lookup_cddb
# 需要导入模块: import CDDB [as 别名]
# 或者: from CDDB import read [as 别名]
def _lookup_cddb(self):
"""
returns a cdinfo() instance containing the information we found in
cddb, or None if that doesn't work. This method doesn't intentionally
throw any exceptions (unlike _lookup_mb) although I'm sure it's
possible.
"""
import DiscID, CDDB
if self.cddevice:
dev = DiscID.open(self.cddevice)
else:
dev = DiscID.open()
cdid = DiscID.disc_id(dev)
tracks = cdid[1]
(status, info) = CDDB.query(cdid)
if status == 200:
(status, info) = CDDB.read(info["category"], info["disc_id"])
elif status == 210 or status == 211:
(status, info) = CDDB.read(info[0]["category"], info[0]["disc_id"])
else:
return None
ret = cdinfo()
for key in info.keys():
if key.startswith("TTITLE"):
n = int(re.findall("TTITLE([0-9]+)", key)[0])
ret.titles[n] = info[key].encode("ascii", errors="replace")
elif key == "DTITLE":
(artist, album) = info[key].split("/")
ret.artist = artist.strip()
ret.album = album.strip()
elif key == "DYEAR":
ret.releasedate = info[key]
wx.LogMessage("cddb succeeded")
return ret
示例11: run
# 需要导入模块: import CDDB [as 别名]
# 或者: from CDDB import read [as 别名]
def run(self):
(status, info) = CDDB.query(self._disc_id,
client_name="dmusic",
client_version="1.0")
if status in [200, 210, 211]:
if status in [210, 211]:
info = sorted(info, key=lambda w: w["category"])
info = info[0]
else:
self.logdebug('Unable to fetch CDDB info, status=%d', status)
(status, info) = CDDB.read(info['category'], info['disc_id'])
if status != 210:
self.logdebug('Unable to fetch CDDB info, status=%d', status)
return
gobject.idle_add(self._cb, self._disc_id, info)
示例12: printDisc
# 需要导入模块: import CDDB [as 别名]
# 或者: from CDDB import read [as 别名]
def printDisc(disc_info):
category = disc_info["category"]
disc_id = disc_info["disc_id"]
title = disc_info["title"]
(track_status, track_info) = CDDB.read(category, disc_id)
print "%s\t(%s)" % (title,category)
tracks = {}
for (k,v) in track_info.items():
if k.find("TTITLE") != -1:
num = int(k[len("TTITLE"):]) + 1
tracks[num] = v
tracks.items().sort()
for (k,v) in tracks.items():
print "%s. %s" % (k,v)
示例13: extractAudioCdInfo
# 需要导入模块: import CDDB [as 别名]
# 或者: from CDDB import read [as 别名]
def extractAudioCdInfo (self):
""" extract the CD info (album art + artist + tracks), and construct the UPnP items"""
self.cdrom = DiscID.open(self.device_name)
disc_id = DiscID.disc_id(self.cdrom)
(query_status, query_info) = CDDB.query(disc_id)
if query_status in (210, 211):
query_info = query_info[0]
(read_status, read_info) = CDDB.read(query_info['category'], query_info['disc_id'])
# print query_info['title']
# print disc_id[1]
# for i in range(disc_id[1]):
# print "Track %.02d: %s" % (i, read_info['TTITLE' + `i`])
track_count = disc_id[1]
disc_id = query_info['disc_id']
self.disc_title = query_info['title'].encode('utf-8')
tracks = {}
for i in range(track_count):
tracks[i + 1] = read_info['TTITLE' + `i`].decode('ISO-8859-1').encode('utf-8')
self.name = self.disc_title
root_item = Container(None, self.disc_title)
# we will sort the item by "track_number"
def childs_sort(x, y):
return cmp(x.track_number, y.track_number)
root_item.sorting_method = childs_sort
self.set_root_item(root_item)
for number, title in tracks.items():
item = TrackItem(self.device_name, number, "Unknown", title)
external_id = "%s_%d" % (disc_id, number)
root_item.add_child(item, external_id=external_id)
self.info('Sharing audio CD %s', self.disc_title)
reactor.callLater(2, self.checkIfAudioCdStillPresent)
self.init_completed()
示例14: saveDisc
# 需要导入模块: import CDDB [as 别名]
# 或者: from CDDB import read [as 别名]
def saveDisc(disc_info):
category = disc_info["category"]
disc_id = disc_info["disc_id"]
title = disc_info["title"]
(artistName, albumName) = disc_info["title"].split("/")
artistName = artistName.strip()
albumName = albumName.strip()
#Search for existing artist
artists = Artist.selectBy(name=artistName)
if artists.count() == 0:
#Create artist
artist = Artist(name=artistName,category=category)
else:
#Use existing artist
artist = artists[0]
#Search for existing album
albums = Album.selectBy(name=albumName)
if albums.count() == 0:
#Create album
album = Album(disc_id=disc_id,name=albumName,artist=artist)
#Create tracks
(track_status, track_info) = CDDB.read(category, disc_id)
tracks = {}
for (k,v) in track_info.items():
if k.find("TTITLE") != -1:
num = int(k[len("TTITLE"):]) + 1
tracks[num] = v
tracks.items().sort()
for (k,v) in tracks.items():
track = Track(num=k,name=v,album=album)
print "***Saved in catalogue***"
else:
print "***Already catalogued***"
printDisc(disc_info)
示例15: _get_information_from_result_element
# 需要导入模块: import CDDB [as 别名]
# 或者: from CDDB import read [as 别名]
def _get_information_from_result_element(self, result, disc_id):
"""Catch any information from a CDDB result dictionnary"""
title = unicode(result['title'], "iso-8859-1")
category = unicode(result['category'], "iso-8859-1")
disc = unicode(result['disc_id'], "iso-8859-1")
self.artist = title[:title.index(' / ')]
self.title = title[title.index(' / ') + 3:]
# Get track titles
info = CDDB.read(category, disc)[1]
for i in range(disc_id[1]):
if i + 4 == len(disc_id):
# We must calculate last track length in a different way
length = disc_id[len(disc_id) - 1] - self.length
else:
# Calculate track length in seconds
length = (disc_id[i + 3] - disc_id[ i + 2]) / 75
self.length += length
track_title = unicode(info['TTITLE' + str(i)], "iso-8859-1")
self.tracks.append(CompactDiscTrack(i + 1, track_title, length))