本文整理汇总了Python中musicbrainz2.utils.extractUuid函数的典型用法代码示例。如果您正苦于以下问题:Python extractUuid函数的具体用法?Python extractUuid怎么用?Python extractUuid使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了extractUuid函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: itunesImport
def itunesImport(pathtoxml):
if os.path.splitext(pathtoxml)[1] == '.xml':
pl = XMLLibraryParser(pathtoxml)
l = Library(pl.dictionary)
lst = []
for song in l.songs:
lst.append(song.artist)
rawlist = {}.fromkeys(lst).keys()
artistlist = [f for f in rawlist if f != None]
else:
rawlist = os.listdir(pathtoxml)
artistlist = [f for f in rawlist if f != '.DS_STORE']
for name in artistlist:
time.sleep(1)
artistResults = ws.Query().getArtists(ws.ArtistFilter(string.replace(name, '&', '%38'), limit=1))
for result in artistResults:
time.sleep(1)
artistid = u.extractUuid(result.artist.id)
inc = ws.ArtistIncludes(releases=(m.Release.TYPE_OFFICIAL, m.Release.TYPE_ALBUM), ratings=False, releaseGroups=False)
artist = ws.Query().getArtistById(artistid, inc)
conn=sqlite3.connect(database)
c=conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS artists (ArtistID TEXT UNIQUE, ArtistName TEXT, ArtistSortName TEXT, DateAdded TEXT, Status TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS albums (ArtistID TEXT, ArtistName TEXT, AlbumTitle TEXT, AlbumASIN TEXT, ReleaseDate TEXT, DateAdded TEXT, AlbumID TEXT UNIQUE, Status TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS tracks (ArtistID TEXT, ArtistName TEXT, AlbumTitle TEXT, AlbumASIN TEXT, AlbumID TEXT, TrackTitle TEXT, TrackDuration TEXT, TrackID TEXT)')
c.execute('SELECT ArtistID from artists')
artistlist = c.fetchall()
if any(artistid in x for x in artistlist):
pass
else:
c.execute('INSERT INTO artists VALUES( ?, ?, ?, CURRENT_DATE, ?)', (artistid, artist.name, artist.sortName, 'Active'))
for release in artist.getReleases():
time.sleep(1)
releaseid = u.extractUuid(release.id)
inc = ws.ReleaseIncludes(artist=True, releaseEvents= True, tracks= True, releaseGroup=True)
results = ws.Query().getReleaseById(releaseid, inc)
for event in results.releaseEvents:
if event.country == 'US':
c.execute('INSERT INTO albums VALUES( ?, ?, ?, ?, ?, CURRENT_DATE, ?, ?)', (artistid, results.artist.name, results.title, results.asin, results.getEarliestReleaseDate(), u.extractUuid(results.id), 'Skipped'))
conn.commit()
c.execute('SELECT ReleaseDate, DateAdded from albums WHERE AlbumID="%s"' % u.extractUuid(results.id))
latestrelease = c.fetchall()
if latestrelease[0][0] > latestrelease[0][1]:
c.execute('UPDATE albums SET Status = "Wanted" WHERE AlbumID="%s"' % u.extractUuid(results.id))
else:
pass
for track in results.tracks:
c.execute('INSERT INTO tracks VALUES( ?, ?, ?, ?, ?, ?, ?, ?)', (artistid, results.artist.name, results.title, results.asin, u.extractUuid(results.id), track.title, track.duration, u.extractUuid(track.id)))
conn.commit()
else:
pass
c.close()
示例2: tagTrack
def tagTrack(self, todoEntry):
import eyeD3
fileName = todoEntry['mp3file'] + '.tmp'
release = todoEntry['release']
track = todoEntry['track']
tag = eyeD3.Tag()
tag.link(str(fileName)) # eyeD3 doesn't like unicode strings
tag.header.setVersion(eyeD3.ID3_V2)
if track.artist is None:
tag.setArtist(release.artist.name)
else:
tag.setArtist(track.artist.name)
tag.setTitle(track.title)
tag.setAlbum(release.title)
tag.setTrackNum( (todoEntry['num'], len(release.tracks)) )
types = (release.TYPE_OFFICIAL, release.TYPE_PROMOTION,
release.TYPE_BOOTLEG)
for t in release.types:
value = extractFragment(t, NS_MMD_1)
if t in types:
tag.addUserTextFrame(ALBUM_TYPE, value)
else:
tag.addUserTextFrame(ALBUM_STATUS, value)
tag.addUserTextFrame(ALBUM_ARTIST, release.artist.name)
tag.addUserTextFrame(ALBUM_ARTIST_SORTNAME,
release.artist.sortName)
tag.addUniqueFileID(FILE_ID, str(extractUuid(track.id)))
if track.artist is None:
tag.addUserTextFrame(ARTIST_ID,
extractUuid(release.artist.id))
else:
tag.addUserTextFrame(ARTIST_ID, extractUuid(track.artist.id))
tag.addUserTextFrame(ALBUM_ID, extractUuid(release.id))
tag.addUserTextFrame(ALBUM_ARTIST_ID,
extractUuid(release.artist.id))
event = release.getEarliestReleaseEvent()
if event is not None:
tag.addUserTextFrame(RELEASE_COUNTRY, event.country)
tag.setDate(event.date[0:4])
tag.update(eyeD3.ID3_V2_3)
示例3: importartist
def importartist(artistlist):
for name in artistlist:
logger.log(u"Querying MusicBrainz for: "+name)
time.sleep(1)
artistResults = ws.Query().getArtists(ws.ArtistFilter(string.replace(name, '&', '%38'), limit=1))
for result in artistResults:
if result.artist.name == 'Various Artists':
logger.log(u"Top result is Various Artists. Skipping.", logger.WARNING)
else:
logger.log(u"Found best match: "+result.artist.name+". Gathering album information...")
time.sleep(1)
artistid = u.extractUuid(result.artist.id)
inc = ws.ArtistIncludes(releases=(m.Release.TYPE_OFFICIAL, m.Release.TYPE_ALBUM), ratings=False, releaseGroups=False)
artist = ws.Query().getArtistById(artistid, inc)
conn=sqlite3.connect(database)
c=conn.cursor()
c.execute('SELECT ArtistID from artists')
artistlist = c.fetchall()
if any(artistid in x for x in artistlist):
logger.log(result.artist.name + u" is already in the database, skipping")
else:
c.execute('INSERT INTO artists VALUES( ?, ?, ?, CURRENT_DATE, ?)', (artistid, artist.name, artist.sortName, 'Active'))
for release in artist.getReleases():
time.sleep(1)
releaseid = u.extractUuid(release.id)
inc = ws.ReleaseIncludes(artist=True, releaseEvents= True, tracks= True, releaseGroup=True)
results = ws.Query().getReleaseById(releaseid, inc)
for event in results.releaseEvents:
if event.country == 'US':
c.execute('INSERT INTO albums VALUES( ?, ?, ?, ?, ?, CURRENT_DATE, ?, ?)', (artistid, results.artist.name, results.title, results.asin, results.getEarliestReleaseDate(), u.extractUuid(results.id), 'Skipped'))
conn.commit()
c.execute('SELECT ReleaseDate, DateAdded from albums WHERE AlbumID="%s"' % u.extractUuid(results.id))
latestrelease = c.fetchall()
if latestrelease[0][0] > latestrelease[0][1]:
c.execute('UPDATE albums SET Status = "Wanted" WHERE AlbumID="%s"' % u.extractUuid(results.id))
else:
pass
for track in results.tracks:
c.execute('INSERT INTO tracks VALUES( ?, ?, ?, ?, ?, ?, ?, ?)', (artistid, results.artist.name, results.title, results.asin, u.extractUuid(results.id), track.title, track.duration, u.extractUuid(track.id)))
conn.commit()
else:
logger.log(results.title + u" is not a US release. Skipping for now")
c.close()
示例4: addArtist
def addArtist(self, artistid):
inc = ws.ArtistIncludes(releases=(m.Release.TYPE_OFFICIAL, m.Release.TYPE_ALBUM), ratings=False, releaseGroups=False)
artist = ws.Query().getArtistById(artistid, inc)
conn=sqlite3.connect(database)
c=conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS artists (ArtistID TEXT UNIQUE, ArtistName TEXT, ArtistSortName TEXT, DateAdded TEXT, Status TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS albums (ArtistID TEXT, ArtistName TEXT, AlbumTitle TEXT, AlbumASIN TEXT, ReleaseDate TEXT, DateAdded TEXT, AlbumID TEXT UNIQUE, Status TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS tracks (ArtistID TEXT, ArtistName TEXT, AlbumTitle TEXT, AlbumASIN TEXT, AlbumID TEXT, TrackTitle TEXT, TrackDuration, TrackID TEXT)')
c.execute('SELECT ArtistID from artists')
artistlist = c.fetchall()
if any(artistid in x for x in artistlist):
page = [templates._header]
page.append('''%s has already been added. Go <a href="/">back</a>.''' % artist.name)
logger.log(artist.name + u" is already in the database!", logger.WARNING)
c.close()
return page
else:
logger.log(u"Adding " + artist.name + " to the database.")
c.execute('INSERT INTO artists VALUES( ?, ?, ?, CURRENT_DATE, ?)', (artistid, artist.name, artist.sortName, 'Active'))
for release in artist.getReleases():
releaseid = u.extractUuid(release.id)
inc = ws.ReleaseIncludes(artist=True, releaseEvents= True, tracks= True, releaseGroup=True)
results = ws.Query().getReleaseById(releaseid, inc)
time.sleep(0.6)
for event in results.releaseEvents:
if event.country == 'US':
logger.log(u"Now adding album: " + results.title+ " to the database")
c.execute('INSERT INTO albums VALUES( ?, ?, ?, ?, ?, CURRENT_DATE, ?, ?)', (artistid, results.artist.name, results.title, results.asin, results.getEarliestReleaseDate(), u.extractUuid(results.id), 'Skipped'))
c.execute('SELECT ReleaseDate, DateAdded from albums WHERE AlbumID="%s"' % u.extractUuid(results.id))
latestrelease = c.fetchall()
if latestrelease[0][0] > latestrelease[0][1]:
logger.log(results.title + u" is an upcoming album. Setting its status to 'Wanted'...")
c.execute('UPDATE albums SET Status = "Wanted" WHERE AlbumID="%s"' % u.extractUuid(results.id))
else:
pass
for track in results.tracks:
c.execute('INSERT INTO tracks VALUES( ?, ?, ?, ?, ?, ?, ?, ?)', (artistid, results.artist.name, results.title, results.asin, u.extractUuid(results.id), track.title, track.duration, u.extractUuid(track.id)))
else:
logger.log(results.title + " is not a US release. Skipping it for now", logger.DEBUG)
conn.commit()
c.close()
raise cherrypy.HTTPRedirect("/")
示例5: artist_info
def artist_info(artist_name):
info = dict(members=None, wikipedia=None, homepage=None)
# short names are bad
if len(artist_name) < 3:
return info
q = ws.Query()
filt = ws.ArtistFilter(artist_name, limit=10)
results = q.getArtists(filt)
results = [x for x in results if x.score >= 99]
# too many high scoring hits, can't disambiguate automatically
if len(results) != 1:
return info
artist = results[0].artist
uuid = mbutils.extractUuid(artist.id)
inc = ws.ArtistIncludes(artistRelations=True, urlRelations=True)
artist = q.getArtistById(uuid, inc)
urls = artist.getRelationTargets(m.Relation.TO_URL, m.NS_REL_1+'Wikipedia')
if len(urls):
info['wikipedia'] = urllib.unquote(urls[0])
urls = artist.getRelationTargets(m.Relation.TO_URL, m.NS_REL_1+'OfficialHomepage')
if len(urls):
info['homepage'] = urllib.unquote(urls[0])
if artist.type == m.Artist.TYPE_GROUP:
members = artist.getRelations(m.Relation.TO_ARTIST, m.NS_REL_1+'MemberOfBand')
addl_uri = m.NS_REL_1+'Additional'
coreMembers = [r for r in members if addl_uri not in r.attributes]
info['members'] = ", ".join([x.target.name for x in coreMembers if not x.endDate])
if info['members'] == "":
info['members'] = None
return info
示例6: findArtist
def findArtist(self, name):
page = [templates._header]
if len(name) == 0 or name == 'Add an artist':
raise cherrypy.HTTPRedirect("home")
else:
artistResults = ws.Query().getArtists(ws.ArtistFilter(string.replace(name, '&', '%38'), limit=8))
if len(artistResults) == 0:
logger.log(u"No results found for " + name)
page.append('''No results!<a class="blue" href="home">Go back</a>''')
return page
elif len(artistResults) > 1:
page.append('''Search returned multiple artists. Click the artist you want to add:<br /><br />''')
for result in artistResults:
artist = result.artist
detail = artist.getDisambiguation()
if detail:
disambiguation = '(%s)' % detail
else:
disambiguation = ''
page.append('''<a href="addArtist?artistid=%s">%s %s</a> (<a class="externalred" href="artistInfo?artistid=%s">more info</a>)<br />''' % (u.extractUuid(artist.id), artist.name, disambiguation, u.extractUuid(artist.id)))
return page
else:
for result in artistResults:
artist = result.artist
logger.log(u"Found one artist matching your search term: " + artist.name +" ("+ artist.id+")")
raise cherrypy.HTTPRedirect("addArtist?artistid=%s" % u.extractUuid(artist.id))
示例7: getUserRating
def getUserRating(self, entityUri):
"""Return the rating a user has applied to an entity.
The given parameter has to be a fully qualified MusicBrainz
ID, as returned by other library functions.
Note that this method only works if a valid user name and
password have been set. Only the rating the authenticated user
applied to the entity will be returned. If username and/or
password are incorrect, an AuthenticationError is raised.
This method will return a L{Rating <musicbrainz2.model.Rating>}
object.
@param entityUri: a string containing an absolute MB ID
@raise ValueError: invalid entityUri
@raise ConnectionError: couldn't connect to server
@raise RequestError: invalid ID or entity
@raise AuthenticationError: invalid user name and/or password
"""
entity = mbutils.extractEntityType(entityUri)
uuid = mbutils.extractUuid(entityUri, entity)
params = { 'entity': entity, 'id': uuid }
stream = self._ws.get('rating', '', filter=params)
try:
parser = MbXmlParser()
result = parser.parse(stream)
except ParseError, e:
raise ResponseError(str(e), e)
示例8: submitISRCs
def submitISRCs(self, tracks2isrcs):
"""Submit track to ISRC mappings.
The C{tracks2isrcs} parameter has to be a dictionary, with the
keys being MusicBrainz track IDs (either as absolute URIs or
in their 36 character ASCII representation) and the values
being ISRCs (ASCII, 12 characters).
Note that this method only works if a valid user name and
password have been set. See the example in L{Query} on how
to supply authentication data.
@param tracks2isrcs: a dictionary mapping track IDs to ISRCs
@raise ConnectionError: couldn't connect to server
@raise RequestError: invalid track or ISRCs
@raise AuthenticationError: invalid user name and/or password
"""
params = [ ]
for (trackId, isrc) in tracks2isrcs.iteritems():
trackId = mbutils.extractUuid(trackId, 'track')
params.append( ('isrc', trackId + ' ' + isrc) )
encodedStr = urllib.urlencode(params, True)
self._ws.post('track', '', encodedStr)
示例9: submitPuids
def submitPuids(self, tracks2puids):
"""Submit track to PUID mappings.
The C{tracks2puids} parameter has to be a dictionary, with the
keys being MusicBrainz track IDs (either as absolute URIs or
in their 36 character ASCII representation) and the values
being PUIDs (ASCII, 36 characters).
Note that this method only works if a valid user name and
password have been set. See the example in L{Query} on how
to supply authentication data.
@param tracks2puids: a dictionary mapping track IDs to PUIDs
@raise ConnectionError: couldn't connect to server
@raise RequestError: invalid track or PUIDs
@raise AuthenticationError: invalid user name and/or password
"""
assert self._clientId is not None, 'Please supply a client ID'
params = [ ]
params.append( ('client', self._clientId.encode('utf-8')) )
for (trackId, puid) in tracks2puids.iteritems():
trackId = mbutils.extractUuid(trackId, 'track')
params.append( ('puid', trackId + ' ' + puid) )
encodedStr = urllib.urlencode(params, True)
self._ws.post('track', '', encodedStr)
示例10: submitUserTags
def submitUserTags(self, entityUri, tags):
"""Submit folksonomy tags for an entity.
Note that all previously existing tags from the authenticated
user are replaced with the ones given to this method. Other
users' tags are not affected.
@param entityUri: a string containing an absolute MB ID
@param tags: A list of either L{Tag <musicbrainz2.model.Tag>} objects
or strings
@raise ValueError: invalid entityUri
@raise ConnectionError: couldn't connect to server
@raise RequestError: invalid ID, entity or tags
@raise AuthenticationError: invalid user name and/or password
"""
entity = mbutils.extractEntityType(entityUri)
uuid = mbutils.extractUuid(entityUri, entity)
params = (
('type', 'xml'),
('entity', entity),
('id', uuid),
('tags', ','.join([unicode(tag).encode('utf-8') for tag in tags]))
)
encodedStr = urllib.urlencode(params)
self._ws.post('tag', '', encodedStr)
示例11: submitUserRating
def submitUserRating(self, entityUri, rating):
"""Submit rating for an entity.
Note that all previously existing rating from the authenticated
user are replaced with the one given to this method. Other
users' ratings are not affected.
@param entityUri: a string containing an absolute MB ID
@param rating: A L{Rating <musicbrainz2.model.Rating>} object
or integer
@raise ValueError: invalid entityUri
@raise ConnectionError: couldn't connect to server
@raise RequestError: invalid ID, entity or tags
@raise AuthenticationError: invalid user name and/or password
"""
entity = mbutils.extractEntityType(entityUri)
uuid = mbutils.extractUuid(entityUri, entity)
params = (
('type', 'xml'),
('entity', entity),
('id', uuid),
('rating', unicode(rating).encode('utf-8'))
)
encodedStr = urllib.urlencode(params)
self._ws.post('rating', '', encodedStr)
示例12: _writeTrack
def _writeTrack(self, xml, track, score=None):
if track is None:
return
xml.start('track', {
'id': mbutils.extractUuid(track.getId()),
'ext:score': score,
})
xml.elem('title', track.getTitle())
xml.elem('duration', str(track.getDuration()))
self._writeArtist(xml, track.getArtist())
if len(track.getReleases()) > 0:
# TODO: offset + count
xml.start('release-list')
for release in track.getReleases():
self._writeRelease(xml, release)
xml.end()
if len(track.getPuids()) > 0:
xml.start('puid-list')
for puid in track.getPuids():
xml.elem('puid', None, { 'id': puid })
xml.end()
self._writeRelationList(xml, track)
# TODO: extensions
xml.end()
示例13: _writeRelation
def _writeRelation(self, xml, rel, targetType):
relAttrs = ' '.join([mbutils.extractFragment(a)
for a in rel.getAttributes()])
if relAttrs == '':
relAttrs = None
attrs = {
'type': mbutils.extractFragment(rel.getType()),
'target': mbutils.extractUuid(rel.getTargetId()),
'direction': rel.getDirection(),
'begin': rel.getBeginDate(),
'end': rel.getBeginDate(),
'attributes': relAttrs,
}
if rel.getTarget() is None:
xml.elem('relation', attrs)
else:
xml.start('relation', attrs)
if targetType == NS_REL_1 + 'Artist':
self._writeArtist(xml, rel.getTarget())
elif targetType == NS_REL_1 + 'Release':
self._writeRelease(xml, rel.getTarget())
elif targetType == NS_REL_1 + 'Track':
self._writeTrack(xml, rel.getTarget())
xml.end()
示例14: _writeLabel
def _writeLabel(self, xml, label, score=None):
if label is None:
return
xml.start('label', {
'id': mbutils.extractUuid(label.getId()),
'type': mbutils.extractFragment(label.getType()),
'ext:score': score,
})
xml.elem('name', label.getName())
xml.elem('sort-name', label.getSortName())
xml.elem('disambiguation', label.getDisambiguation())
xml.elem('life-span', None, {
'begin': label.getBeginDate(),
'end': label.getEndDate(),
})
if len(label.getAliases()) > 0:
xml.start('alias-list')
for alias in label.getAliases():
xml.elem('alias', alias.getValue(), {
'type': alias.getType(),
'script': alias.getScript(),
})
xml.end()
# TODO: releases, artists
self._writeRelationList(xml, label)
# TODO: extensions
xml.end()
示例15: uuid_from_soup
def uuid_from_soup(soup, type = None):
uuid_link = soup.find('a', href=MB_PATTERN)
if uuid_link:
try:
return extractUuid(uuid_link['href'], type)
except ValueError:
pass # Not a valid UUID for some reason?
return None