本文整理汇总了Python中stagger.read_tag函数的典型用法代码示例。如果您正苦于以下问题:Python read_tag函数的具体用法?Python read_tag怎么用?Python read_tag使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了read_tag函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testID3v2ExtendedHeader
def testID3v2ExtendedHeader(self):
# First sample simply includes an empty extended header.
tag1 = stagger.read_tag(os.path.join(sample_dir,
"23.synthetic.empty-extended-header.lossy.id3"))
self.assertEqual(tag1.title, "The Millionaire's Holiday")
self.assertEqual(tag1.album, "Best Of Combustible Edison")
self.assertEqual(tag1.date, "1997")
self.assertEqual(tag1.track, 1)
self.assertEqual(tag1.genre, "Foobar")
self.assertEqual(tag1.artist, "Combustible Edison")
self.assertEqual(tag1.comment, " 0000132D 0000132D 00002FF0")
self.assertEqual(tag1.flags, { "extended_header" })
# Second sample file has an (invalid) CRC32 number in its extended header.
tag2 = stagger.read_tag(os.path.join(sample_dir,
"23.synthetic.extended-header-bad-crc.lossy.id3"))
self.assertEqual(tag2.title, "The Millionaire's Holiday")
self.assertEqual(tag2.album, "Best Of Combustible Edison")
self.assertEqual(tag2.date, "1997")
self.assertEqual(tag2.track, 1)
self.assertEqual(tag2.genre, "Foobar")
self.assertEqual(tag2.artist, "Combustible Edison")
self.assertEqual(tag2.comment, " 0000132D 0000132D 00002FF0")
self.assertEqual(tag2.flags, { "ext:crc_present", "extended_header" })
self.assertEqual(tag2.crc32, 0x20202020)
示例2: addID3
def addID3(self, title, title2, artist):
print("Tagging "+"{0}.mp3".format(title))
try:
t = stagger.read_tag("{0}.mp3".format(title))
except:
# Try to add an empty ID3 header.
# As long stagger crashes when there's no header, use this hack.
# ID3v2 infos : http://id3.org/id3v2-00
m = open("{0}.mp3".format(title), 'r+b')
old = m.read()
m.seek(0)
m.write(b"\x49\x44\x33\x02\x00\x00\x00\x00\x00\x00" + old) # Meh...
m.close
# Let's try again...
try:
t = stagger.read_tag("{0}.mp3".format(title))
# Slicing is to get the whole track name
# because SoundCloud titles usually have
# a dash between the artist and some name
split = title2.find("-")
if not split == -1:
t.title = title2[(split + 2):]
t.artist = title2[:split]
else:
t.title = title2
t.artist = artist
t.write()
except:
print("[Warning] Can't add tags, skipped.")
示例3: get_ID3_tags
def get_ID3_tags(self, album, file_path):
try:
album.artist = stagger.read_tag(file_path).artist
album.title = stagger.read_tag(file_path).album
if not album.artist or not album.title:
return None
return True
except stagger.errors.NoTagError:
return None
示例4: test_write_id3
def test_write_id3(self):
""" Test write id3 tags """
sandbox = os.path.dirname(os.path.realpath(__file__)) + "/sandbox/"
sample = os.path.dirname(os.path.realpath(__file__)) + "/samples/"
filename = "92583301-dem-beats-3.mp3"
if not os.path.exists(sandbox):
os.mkdir(sandbox)
shutil.copyfile(sample + filename, sandbox + filename)
tag = stag()
tag._process_artwork_tmpfile = Mock(return_value=False)
client = Mock()
track = strack(json_obj[0], client=client)
tag.load_id3(track)
tag.write_id3(sandbox + filename)
res = stagger.read_tag(sandbox + filename)
self.assertEqual("Some text", res[TIT1].text[0])
self.assertEqual("Foo", res[TIT2].text[0])
self.assertEqual("dubstep bass", res[TIT3].text[0])
self.assertEqual("247010", res[TLEN].text[0])
self.assertEqual("foo", res[TOFN].text[0])
self.assertEqual("Dubstep", res[TCON].text[0])
self.assertEqual("free", res[TCOP].text[0])
self.assertEqual("1387373820", res[TDOR].text[0])
self.assertEqual("https://foobar.dev/1337", res[WOAS].url)
self.assertEqual("https://api.foobar.dev/1337", res[WOAF].url)
self.assertEqual("user1", res[TPUB].text[0])
self.assertEqual("http://user1.dev", res[WOAR][0].url)
self.assertEqual("User 1", res[TPE1].text[0])
self.assertEqual("User 1 Soundcloud tracks", res[TALB].text[0])
shutil.rmtree(sandbox)
示例5: copySongs
def copySongs(source,target):
windows = True
win = "\\"
lin = "/"
os.chdir(source)
a = [ name for name in os.listdir(os.getcwd()) if os.path.isdir(os.path.join(os.getcwd(), name)) ]
for x in a:
os.chdir(source)
os.chdir(x)
b = [ name for name in os.listdir(os.getcwd()) if os.path.isfile(os.path.join(os.getcwd(), name)) ]
for y in b:
os.chdir(source)
os.chdir(x)
oldfilename = os.getcwd()+"\\"+y
try:
tag = stagger.read_tag(y)
title = removeSymbols(tag.title.strip())
artist = removeSymbols(tag.artist.strip())
trackNr = tag.track
album = removeSymbols(tag.album.strip())
filename = str(trackNr)+" - "+title+".mp3"
except:
title = y
artist = "NO ID3 TAG"
trackNr = random.randint(0, 20)
album = "NoAlbum"
filename = str(trackNr)+" - "+title
if len(album) > 0:
if windows:
fullpath = target+win+artist+win+album+win
else:
fullpath = target+lin+artist+lin+album+lin
else:
if windows:
fullpath = target+win+artist+win+"NoAlbum"+win
else:
fullpath = target+lin+artist+lin+"NoAlbum"+lin
fullfilepath = fullpath+filename
if os.path.exists(r''+fullfilepath+''):
pass
else:
if windows:
if os.path.exists(r''+target+win+artist):
os.chdir(r''+target+win+artist)
else:
os.mkdir(r''+target+win+artist)
os.chdir(r''+target+win+artist)
else:
if os.path.exists(r''+target+lin+artist):
os.chdir(r''+target+lin+artist)
else:
os.mkdir(r''+target+lin+artist)
os.chdir(r''+target+lin+artist)
if os.path.exists(r''+fullpath):
os.chdir(r''+fullpath)
else:
os.mkdir(r''+fullpath)
os.chdir(r''+fullpath)
print(fullfilepath)
shutil.copyfile(r''+oldfilename+'', r''+fullfilepath+'')
示例6: add_location
def add_location(location):
entry = {}
entry['location'] = location
entry['encoding'] = encoding.from_file(location.encode('utf-8')).decode('utf-8')
entry['mime'] = mime.from_file(location.encode('utf-8')).decode('utf-8')
if os.path.isdir(location):
entry['type'] = 'folder'
elif os.path.isfile(location):
entry['type'] = 'file'
(root, ext) = os.path.splitext(location)
if ext:
entry['extension'] = ext[1:]
if ext[1:].lower() == 'mp3':
print(location)
tag = stagger.read_tag(location)
for t in tag.values():
print(t)
print(tag.title)
print(tag.comment)
'''
try:
tag = stagger.read_tag(location)
for t in tag.values():
print(t)
print(t.comment)
except:
# No tag:w
pass
'''
sys.exit()
示例7: db_insert_file
def db_insert_file(filename, file):
"""Reads file metadata and inserts it into the database."""
id3_file = None
try:
id3_file = read_tag(path.join(app.config["UPLOAD_FOLDER"], filename))
except NoTagError:
# No ID3 tags whatsoever
print("Inserting misc file: " + filename)
query = "INSERT IGNORE INTO ytfs_meta (filename) VALUES ('{0}');".format(filename)
cursor.execute(query)
db.commit()
return
track = id3_file.track if id3_file.track is not None else 0
title = id3_file.title.replace("'", "\\'")
artist = id3_file.artist.replace("'", "\\'")
album = id3_file.album.replace("'", "\\'")
year = id3_file.date.replace("'", "\\'")
genre = id3_file.genre.replace("'", "\\'")
track_comment = id3_file.comment.replace("'", "\\'")
print("Inserting: " + artist + " - " + title)
query = "INSERT IGNORE INTO ytfs_meta (filename, track, title, artist, album, year, genre, track_comment) " + \
"VALUES ('{0}', {1}, '{2}', '{3}', '{4}', '{5}', '{6}', '{7}');".format( \
filename, track, title, artist, album, year, genre, track_comment
)
cursor.execute(query)
db.commit() # Save changes back to DB
示例8: load_id3
def load_id3(path):
data = {}
keys = ['album', 'album_artist', 'artist', 'composer', 'genre',
'sort_album', 'sort_album_artist', 'sort_artist',
'sort_composer', 'sort_title', 'title',
'track_total', 'date'
]
multikeys = {
'album': 'albums',
'album_artist': 'artists',
'artist': 'artists',
'composer': 'composers',
'genre': 'genres',
'sort_album': 'albums',
'sort_album_artist': 'artists',
'sort_artist': 'artists',
'sort_composer': 'composers'
}
tag = stagger.read_tag(path)
for key in keys:
if not hasattr(tag, key):
continue
obj = getattr(tag, key)
if isinstance(obj, Number) or \
(isinstance(obj, str) and \
len(obj) > 0):
data[key] = obj
if key in multikeys:
mkey = multikeys[key]
if mkey not in data:
data[mkey] = []
if obj not in data[mkey]:
data[mkey].append(obj)
return data
示例9: get
def get(self, track_id):
self.set_header("Content-Type", "application/json")
filepath = library[int(track_id)]["filepath"]
tag = stagger.read_tag(filepath)
ret_obj = {}
ret_obj["artist"] = tag.artist
# if 'APIC' in tag._frames:
# apic_frame = tag._frames['APIC']
# ret_obj["albumart"] = []
# for art in apic_frame:
# m = hashlib.md5()
# m.update(art.data)
# hashdata = m.digest()
# hash = base64.b16encode(hashdata).decode("ASCII")
# if not hash in image_dict:
# image_dict[hash] = {
# "mimetype": art.mime,
# "data": art.data
# }
# ret_obj["albumart"].append(hash)
self.write(json.dumps(ret_obj))
示例10: scan_path
def scan_path(session, not_found, path):
url = urlunparse(('file', '', path, '', '', ''))
if url in not_found:
del not_found[url]
return
LOG.debug('Scanning {0}.'.format(path))
try:
tag = read_tag(path)
if not (tag and tag.artist and tag.title):
LOG.warn('No ID3 for {0}.'.format(path))
return
try:
artist = session.query(LocalArtist).filter(LocalArtist.name == tag.artist).one()
except NoResultFound:
artist = LocalArtist(name=tag.artist)
session.add(artist)
track = LocalTrack(url=url, name=tag.title, local_artist=artist)
session.add(track)
session.commit()
except UnicodeEncodeError as e:
LOG.warn('Cannot encode ID3 for {0} ({1}).'.format(path, e))
session.rollback()
except NoTagError as e:
LOG.warn('Cannot read ID3 for {0} ({1}).'.format(path, e))
except ValueError as e:
LOG.warn('Cannot read ID3 for {0} ({1}).'.format(path, e))
示例11: writeTag
def writeTag(file, songartist, song, show):
"write tag info. for some reason this won't work as root"
tag = stagger.read_tag(file)
tag.title = song
tag.artist = songartist
tag.album = show
tag.write()
示例12: process_file
def process_file(self, f):
track = stagger.read_tag(f)
self._titles.append(Title(track.title, track.artist,
1,#track[TLEN].text[0],
f, int(track[TBPM].text[0]),
track[TKEY].text[0],
track.genre))
示例13: sortFile
def sortFile(name, root, dirs):
sFile = NewFile(name)
sFile.root = root
sFile.path = os.path.join(root, name)
if sFile.root != fromLocation:
sFile.baselevel = False
# set the type of file
if sFile.name.endswith(videoFileExt):
sFile.type = "video"
elif sFile.name.endswith(musicFileExt):
sFile.type = "music"
elif sFile.name.endswith(imageFileExt):
sFile.type = "image"
else:
sFile.type = "NA"
if sFile.type == "video":
# only care about season info if its a video
for list in fileSeason:
regex = re.compile(list)
list2 = regex.findall(name)
for l in list2:
if l != "":
sFile.l1 = l
sFile.hasseason = True
if len(sFile.l1) == 6:
sFile.seasonnum = int(sFile.l1[1:3])
if len(sFile.l1) == 4:
sFile.seasonnum = int(sFile.l1[1:2])
if sFile.type == "video":
if sFile.hasseason == True:
# shows
# find Show Folder
tmpPath = findFolder("folder", sFile.name, showFolder.path, str(sFile.seasonnum))
if sFile.seasonnum != 0:
# find season Folder
tmpPath = findFolder("season", str(sFile.seasonnum), tmpPath, str(sFile.seasonnum))
sFile.moveto = tmpPath
else:
# Movies
sFile.moveto = movieFolder.path
elif sFile.type == "image":
sFile.moveto = picFolder.path
elif sFile.type == "music":
tmpPath = ""
audiofile = stagger.read_tag(sFile.path)
tmpPath = findFolder("folder", audiofile.artist, musicFolder.path, "")
tmpPath = findFolder("folder", audiofile.album, tmpPath, "")
sFile.moveto = tmpPath
if sFile.moveto != "":
writeReport( sFile.path + " was moved to " + sFile.moveto + "\\" + sFile.name + "\n")
if not os.path.exists(sFile.moveto + "\\" + sFile.name):
shutil.copy(sFile.path, sFile.moveto + "\\" + sFile.name)
with printLock:
print(sFile.name)
示例14: tagPath
def tagPath(mp3s):
"""Return a path built from the tags of the given mp3 files."""
tagPaths = []
for mp3 in mp3s:
tag = stagger.read_tag(mp3)
tagPaths.append(os.path.join(tag.artist, tag.album,
" ".join(["{0:02d}".format(tag.track), tag.title])
))
return tagPaths
示例15: tag
def tag(self, music_file: DownloadedMusicFile):
tags = self.__parse_tags(music_file)
audio_tags = stagger.read_tag(music_file.file_mp3)
audio_tags.album = tags.album
audio_tags.artist = tags.artist
audio_tags.title = tags.title
audio_tags.picture = tags.file_thumbnail
audio_tags.write()