/
util.py
109 lines (72 loc) · 2.51 KB
/
util.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
import subprocess
import chardet
from color import green, yellow, red
from cuesheet.cueyacc import parsecuedata
class MyException(Exception):
def __init__(self, *args):
self.message = args[0]
super(MyException, self).__init__(args)
class CommandNotFoundError(MyException):
pass
class EncodingError(MyException):
pass
class NoCuedataError(MyException):
pass
support_text_encodings = [ 'ascii',
'latin1',
'utf-8',
'cp936', 'gb18030', 'gb2312', 'gbk',
'shift_jis',
]
def check_command_available( command, reminder="" ):
commands = "which %s 2>/dev/null >/dev/null" % (command)
exitcode = subprocess.call( commands, shell=True)
if exitcode != 0 :
msg = "command '%s' is not found." % (command)
msg += reminder
raise CommandNotFoundError( msg)
def guess_text_encoding(text):
guess = chardet.detect(text)
encoding = guess['encoding']
confidence = guess['confidence']
if not encoding :
raise EncodingError("failed to detect the encoding")
encoding = encoding.lower()
if confidence < 0.98 :
raise EncodingError("encoding detected as '%s' with low confidence '%s'"
% (encoding, confidence) )
elif encoding not in support_text_encodings :
raise EncodingError("encoding '%s' is not well supported yet."
% encoding )
else:
if encoding in ['gbk', 'gb2312', 'cp936' ] :
encoding = 'gb18030'
return encoding
def conv2unicode(text):
if type(text) == unicode :
return text
encoding = guess_text_encoding(text)
result = unicode( text.decode(encoding) )
return result
def parsecuefile(cuefile):
if not cuefile:
raise NoCuedataError("No cuefile is specified/found.")
cuedata = open(cuefile).read()
infomsg ( ("parsing cuefile: %s...") % (cuefile) )
cuedata = conv2unicode(cuedata)
return parsecuedata(cuedata)
def normalize_filename(filename):
"""
fix invalid chars within filename
"""
# "/" is invalid in filename
filename = filename.replace( "/", "-")
return filename
def infomsg (text):
print (green( "[info] %s" % (text) ) )
def warnmsg (text):
print (yellow( "[warning] %s" % (text) ) )
def errormsg (text):
print (red( "[error] %s" % (text) ) )