2to3 autoconvert

This commit is contained in:
NicoHood 2016-08-27 17:42:01 +02:00
parent 406050c382
commit bfb4d11027

View file

@ -2,7 +2,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import sys import sys
import struct import struct
import urllib import urllib.request, urllib.parse, urllib.error
import os import os
import hashlib import hashlib
import mutagen import mutagen
@ -39,7 +39,7 @@ def hash_error_unicode(item):
def validate_unicode(path): def validate_unicode(path):
path_list = path.split('/') path_list = path.split('/')
last_raise = False last_raise = False
for i in xrange(len(path_list)): for i in range(len(path_list)):
if raises_unicode_error(path_list[i]): if raises_unicode_error(path_list[i]):
path_list[i] = hash_error_unicode(path_list[i]) path_list[i] = hash_error_unicode(path_list[i])
last_raise = True last_raise = True
@ -61,11 +61,11 @@ def splitpath(path):
return path.split(os.sep) return path.split(os.sep)
def get_relpath(path, basepath): def get_relpath(path, basepath):
commonprefix = os.sep.join(os.path.commonprefix(map(splitpath, [path, basepath]))) commonprefix = os.sep.join(os.path.commonprefix(list(map(splitpath, [path, basepath]))))
return os.path.relpath(path, commonprefix) return os.path.relpath(path, commonprefix)
def is_path_prefix(prefix, path): def is_path_prefix(prefix, path):
return prefix == os.sep.join(os.path.commonprefix(map(splitpath, [prefix, path]))) return prefix == os.sep.join(os.path.commonprefix(list(map(splitpath, [prefix, path]))))
def group_tracks_by_id3_template(tracks, template): def group_tracks_by_id3_template(tracks, template):
grouped_tracks_dict = {} grouped_tracks_dict = {}
@ -101,21 +101,21 @@ class Text2Speech(object):
# Check for pico2wave voiceover # Check for pico2wave voiceover
if not exec_exists_in_path("pico2wave"): if not exec_exists_in_path("pico2wave"):
Text2Speech.valid_tts['pico2wave'] = False Text2Speech.valid_tts['pico2wave'] = False
print "Warning: pico2wave not found, voicever won't be generated using it." print("Warning: pico2wave not found, voicever won't be generated using it.")
else: else:
voiceoverAvailable = True voiceoverAvailable = True
# Check for espeak voiceover # Check for espeak voiceover
if not exec_exists_in_path("espeak"): if not exec_exists_in_path("espeak"):
Text2Speech.valid_tts['espeak'] = False Text2Speech.valid_tts['espeak'] = False
print "Warning: espeak not found, voicever won't be generated using it." print("Warning: espeak not found, voicever won't be generated using it.")
else: else:
voiceoverAvailable = True voiceoverAvailable = True
# Check for Russian RHVoice voiceover # Check for Russian RHVoice voiceover
if not exec_exists_in_path("RHVoice"): if not exec_exists_in_path("RHVoice"):
Text2Speech.valid_tts['RHVoice'] = False Text2Speech.valid_tts['RHVoice'] = False
print "Warning: RHVoice not found, Russian voicever won't be generated." print("Warning: RHVoice not found, Russian voicever won't be generated.")
else: else:
voiceoverAvailable = True voiceoverAvailable = True
@ -132,8 +132,8 @@ class Text2Speech(object):
return True return True
# ensure we deal with unicode later # ensure we deal with unicode later
if not isinstance(text, unicode): if not isinstance(text, str):
text = unicode(text, 'utf-8') text = str(text, 'utf-8')
lang = Text2Speech.guess_lang(text) lang = Text2Speech.guess_lang(text)
if lang == "ru-RU": if lang == "ru-RU":
return Text2Speech.rhvoice(out_wav_path, text) return Text2Speech.rhvoice(out_wav_path, text)
@ -149,7 +149,7 @@ class Text2Speech(object):
@staticmethod @staticmethod
def guess_lang(unicodetext): def guess_lang(unicodetext):
lang = 'en-GB' lang = 'en-GB'
if re.search(u"[А-Яа-я]", unicodetext) is not None: if re.search("[А-Яа-я]", unicodetext) is not None:
lang = 'ru-RU' lang = 'ru-RU'
return lang return lang
@ -196,7 +196,7 @@ class Record(object):
self.trackgain = parent.trackgain self.trackgain = parent.trackgain
def __getitem__(self, item): def __getitem__(self, item):
if item not in self._struct.keys(): if item not in list(self._struct.keys()):
raise KeyError raise KeyError
return self._fields.get(item, self._struct[item][1]) return self._fields.get(item, self._struct[item][1])
@ -205,7 +205,7 @@ class Record(object):
def construct(self): def construct(self):
output = "" output = ""
for i in self._struct.keys(): for i in list(self._struct.keys()):
(fmt, default) = self._struct[i] (fmt, default) = self._struct[i]
output += struct.pack("<" + fmt, self._fields.get(i, default)) output += struct.pack("<" + fmt, self._fields.get(i, default))
return output return output
@ -364,19 +364,19 @@ class Track(Record):
try: try:
audio = mutagen.File(filename, easy = True) audio = mutagen.File(filename, easy = True)
except: except:
print "Error calling mutagen. Possible invalid filename/ID3Tags (hyphen in filename?)" print("Error calling mutagen. Possible invalid filename/ID3Tags (hyphen in filename?)")
if audio: if audio:
# Note: Rythmbox IPod plugin sets this value always 0. # Note: Rythmbox IPod plugin sets this value always 0.
self["stop_at_pos_ms"] = int(audio.info.length * 1000) self["stop_at_pos_ms"] = int(audio.info.length * 1000)
artist = audio.get("artist", [u"Unknown"])[0] artist = audio.get("artist", ["Unknown"])[0]
if artist in self.artists: if artist in self.artists:
self["artistid"] = self.artists.index(artist) self["artistid"] = self.artists.index(artist)
else: else:
self["artistid"] = len(self.artists) self["artistid"] = len(self.artists)
self.artists.append(artist) self.artists.append(artist)
album = audio.get("album", [u"Unknown"])[0] album = audio.get("album", ["Unknown"])[0]
if album in self.albums: if album in self.albums:
self["albumid"] = self.albums.index(album) self["albumid"] = self.albums.index(album)
else: else:
@ -384,10 +384,10 @@ class Track(Record):
self.albums.append(album) self.albums.append(album)
if audio.get("title", "") and audio.get("artist", ""): if audio.get("title", "") and audio.get("artist", ""):
text = u" - ".join(audio.get("title", u"") + audio.get("artist", u"")) text = " - ".join(audio.get("title", "") + audio.get("artist", ""))
# Handle the VoiceOverData # Handle the VoiceOverData
if isinstance(text, unicode): if isinstance(text, str):
text = text.encode('utf-8', 'ignore') text = text.encode('utf-8', 'ignore')
self["dbid"] = hashlib.md5(text).digest()[:8] #pylint: disable-msg=E1101 self["dbid"] = hashlib.md5(text).digest()[:8] #pylint: disable-msg=E1101
self.text_to_speech(text, self["dbid"]) self.text_to_speech(text, self["dbid"])
@ -424,7 +424,7 @@ class PlaylistHeader(Record):
playlistcount += 1 playlistcount += 1
chunks += [construction] chunks += [construction]
else: else:
print "Error: Playlist does not contain a single track. Skipping playlist." print("Error: Playlist does not contain a single track. Skipping playlist.")
self["number_of_playlists"] = playlistcount self["number_of_playlists"] = playlistcount
self["total_length"] = 0x14 + (self["number_of_playlists"] * 4) self["total_length"] = 0x14 + (self["number_of_playlists"] * 4)
@ -478,7 +478,7 @@ class Playlist(Record):
dataarr = i.strip().split("=", 1) dataarr = i.strip().split("=", 1)
if dataarr[0].lower().startswith("file"): if dataarr[0].lower().startswith("file"):
num = int(dataarr[0][4:]) num = int(dataarr[0][4:])
filename = urllib.unquote(dataarr[1]).strip() filename = urllib.parse.unquote(dataarr[1]).strip()
if filename.lower().startswith('file://'): if filename.lower().startswith('file://'):
filename = filename[7:] filename = filename[7:]
if self.rename: if self.rename:
@ -559,8 +559,8 @@ class Playlist(Record):
except: except:
# Print an error if no track was found. # Print an error if no track was found.
# Empty playlists are handeled in the PlaylistHeader class. # Empty playlists are handeled in the PlaylistHeader class.
print "Error: Could not find track \"" + path + "\"." print("Error: Could not find track \"" + path + "\".")
print "Maybe its an invalid FAT filesystem name. Please fix your playlist. Skipping track." print("Maybe its an invalid FAT filesystem name. Please fix your playlist. Skipping track.")
if position > -1: if position > -1:
chunks += struct.pack("I", position) chunks += struct.pack("I", position)
self["number_of_songs"] += 1 self["number_of_songs"] += 1
@ -592,11 +592,11 @@ class Shuffler(object):
make_dir_if_absent(os.path.join(self.path, dirname)) make_dir_if_absent(os.path.join(self.path, dirname))
def dump_state(self): def dump_state(self):
print "Shuffle DB state" print("Shuffle DB state")
print "Tracks", self.tracks print("Tracks", self.tracks)
print "Albums", self.albums print("Albums", self.albums)
print "Artists", self.artists print("Artists", self.artists)
print "Playlists", self.lists print("Playlists", self.lists)
def populate(self): def populate(self):
self.tunessd = TunesSD(self) self.tunessd = TunesSD(self)
@ -631,14 +631,14 @@ class Shuffler(object):
try: try:
f.write(self.tunessd.construct()) f.write(self.tunessd.construct())
except IOError as e: except IOError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror) print("I/O error({0}): {1}".format(e.errno, e.strerror))
print "Error: Writing iPod database failed." print("Error: Writing iPod database failed.")
sys.exit(1) sys.exit(1)
print "Database written successfully:" print("Database written successfully:")
print "Tracks", len(self.tracks) print("Tracks", len(self.tracks))
print "Albums", len(self.albums) print("Albums", len(self.albums))
print "Artists", len(self.artists) print("Artists", len(self.artists))
print "Playlists", len(self.lists) print("Playlists", len(self.lists))
# #
# Read all files from the directory # Read all files from the directory
@ -657,7 +657,7 @@ def check_unicode(path):
if raises_unicode_error(item): if raises_unicode_error(item):
src = os.path.join(path, item) src = os.path.join(path, item)
dest = os.path.join(path, hash_error_unicode(item)) + os.path.splitext(item)[1].lower() dest = os.path.join(path, hash_error_unicode(item)) + os.path.splitext(item)[1].lower()
print 'Renaming %s -> %s' % (src, dest) print('Renaming %s -> %s' % (src, dest))
os.rename(src, dest) os.rename(src, dest)
else: else:
ret_flag = (check_unicode(os.path.join(path, item)) or ret_flag) ret_flag = (check_unicode(os.path.join(path, item)) or ret_flag)
@ -665,7 +665,7 @@ def check_unicode(path):
src = os.path.join(path, item) src = os.path.join(path, item)
new_name = hash_error_unicode(item) new_name = hash_error_unicode(item)
dest = os.path.join(path, new_name) dest = os.path.join(path, new_name)
print 'Renaming %s -> %s' % (src, dest) print('Renaming %s -> %s' % (src, dest))
os.rename(src, dest) os.rename(src, dest)
return ret_flag return ret_flag
@ -681,15 +681,15 @@ def nonnegative_int(string):
def checkPathValidity(path): def checkPathValidity(path):
if not os.path.isdir(result.path): if not os.path.isdir(result.path):
print "Error finding IPod directory. Maybe it is not connected or mounted?" print("Error finding IPod directory. Maybe it is not connected or mounted?")
sys.exit(1) sys.exit(1)
if not os.access(result.path, os.W_OK): if not os.access(result.path, os.W_OK):
print 'Unable to get write permissions in the IPod directory' print('Unable to get write permissions in the IPod directory')
sys.exit(1) sys.exit(1)
def handle_interrupt(signal, frame): def handle_interrupt(signal, frame):
print "Interrupt detected, exiting..." print("Interrupt detected, exiting...")
sys.exit(1) sys.exit(1)
if __name__ == '__main__': if __name__ == '__main__':
@ -741,8 +741,8 @@ if __name__ == '__main__':
# Print each argument separately so caller doesn't need to # Print each argument separately so caller doesn't need to
# stuff everything to be printed into a single string # stuff everything to be printed into a single string
for arg in args: for arg in args:
print arg, print(arg, end=' ')
print print()
else: else:
verboseprint = lambda *a: None # do-nothing function verboseprint = lambda *a: None # do-nothing function
@ -755,7 +755,7 @@ if __name__ == '__main__':
verboseprint("Track voiceover requested:", result.track_voiceover) verboseprint("Track voiceover requested:", result.track_voiceover)
if (result.track_voiceover or result.playlist_voiceover): if (result.track_voiceover or result.playlist_voiceover):
if not Text2Speech.check_support(): if not Text2Speech.check_support():
print "Error: Did not find any voiceover program. Voiceover disabled." print("Error: Did not find any voiceover program. Voiceover disabled.")
result.track_voiceover = False result.track_voiceover = False
result.playlist_voiceover = False result.playlist_voiceover = False
else: else: