-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathm4bt
executable file
·344 lines (279 loc) · 10.8 KB
/
m4bt
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import argparse
import re
import os
import shutil
import logging
import unicodedata
from mutagen.mp4 import MP4
AUTHOR = ''
ALBUM = ''
TITLE = ""
FILENAME = ''
SPEAKER = ''
SERIES = ''
COMMENT = ''
MOVE = False
RENAME = False
DRYRUN = False
DIR = ''
LOGLEVEL = logging.WARNING
parser = argparse.ArgumentParser(
prog='m4bt',
description='Progtam to add tags to audiobooks and move and/or rename them',
epilog='-=*=-')
parser.add_argument('-a', '--author', dest="author", help='Audiobook Author' )
parser.add_argument('-A', '--album', dest="album", help="Audiobook album name")
parser.add_argument('-t', '--title', dest="title", help="Audiobook Title")
parser.add_argument('-S', '--series', dest="series", help="Audiobook Series")
parser.add_argument('-s', '--speaker', dest="speaker", help="Audiobook Speaker/Narrover")
parser.add_argument('-C', '--comment', dest="comment", help="Audiobook Comment")
parser.add_argument('-v', '--verbose', dest="verbose", action='store_true', help="verbose output")
parser.add_argument('-m', dest='move', action='store_true', help="Move Audiobook to specific directory structure")
parser.add_argument('-r', dest='rename', action='store_true', help='Rename Audiobook file by tags')
parser.add_argument('-d', dest='dryrun', action='store_true', help='DryRun action. Do not change anythiing')
parser.add_argument( '--debug', dest='debug' , action='store_true', help='Debug output')
parser.add_argument('filenames', type=str, nargs='+', help='Audiobook filenames',)
args = parser.parse_args()
MOVE = args.move
RENAME = args.rename
DRYRUN = args.dryrun
VERBOSE = logging.INFO if args.verbose else LOGLEVEL
LOGLEVEL = logging.DEBUG if args.debug else LOGLEVEL
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=LOGLEVEL)
logging.debug("File Names: "+str(args.filenames) )
def mkpath(tags):
logging.debug(f"Creating directory name by tags")
if '\xa9ART' not in tags:
print("Please set Author")
os.exit(99)
author = tags['\xa9ART'][0]
if '\xa9nam' not in tags:
print("Please set Name")
os.exit(99)
name = tags['\xa9nam'][0]
series = ''
if "tvsh" in tags and tags['tvsh']:
series = tags['tvsh'][0]
album = ''
if "\xa9alb" in tags and tags['\xa9alb']:
album = tags['\xa9alb'][0]
else:
album = name
speaker = ''
if '\xa9wrt' in tags and tags['\xa9wrt']:
speaker=tags['\xa9wrt'][0]
comment = ''
if '\xa9cmt' in tags and tags['\xa9cmt']:
comment=tags['\xa9cmt'][0]
logging.debug(f"Title: {name}")
logging.debug(f"album: {album}")
logging.debug(f"Series: {series}")
logging.debug(f"Speaker: {speaker}")
logging.debug(f"Comment: {comment}")
if album and series and album == name:
#cut series from name
k = re.compile( "%s.? (.+)" % (series) )
pname=name
if k.match(name):
pname = k.search( str(name) ).group(1)
logging.debug("Dir [album and series, album == title]: %s/%s/%s" % (author, series, pname ))
DIR= "%s/%s/%s" % (author, series, pname )
elif album and series and album != name:
#cut series from name
# k = re.compile( "%s.? (.+)" % (series) )
# pname=name
# if k.match(name):
# pname = k.search( str(name) ).group(1)
logging.debug("Dir [album and series, album != title]: %s/%s/%s" % (author, series, album ))
DIR= "%s/%s/%s" % (author, series, album )
elif album and not series:
logging.debug("Dir [album and not series]: %s/%s" % (author, album ))
DIR= "%s/%s" % (author, album )
elif series and not ALBUM:
# Cut series name from File name
k = re.compile( "%s.? (.+)" % (series) )
pname=name
if k.match(name):
pname = k.search( str(name) ).group(1)
DIR= "%s/%s/%s" % (author, series, pname )
else:
DIR= "%s/%s" % (author, pname )
logging.debug(f"Path : {DIR}")
return DIR
def mkfilename(tags):
logging.debug(f"Creating file name by tags")
if '\xa9ART' not in tags:
print("Please set Author")
os.exit(99)
author = tags['\xa9ART'][0]
if '\xa9nam' not in tags:
print("Please set Name")
os.exit(99)
name = tags['\xa9nam'][0]
series = ''
if "tvsh" in tags and tags['tvsh']:
series = tags['tvsh'][0]
album = ''
if "\xa9alb" in tags and tags['\xa9alb']:
album = tags['\xa9alb'][0]
else:
album = name
speaker = ''
if '\xa9wrt' in tags and tags['\xa9wrt']:
speaker=tags['\xa9wrt'][0]
comment = ''
if '\xa9cmt' in tags and tags['\xa9cmt']:
comment=tags['\xa9cmt'][0]
logging.debug(f"Title: {name}")
logging.debug(f"album: {album}")
logging.debug(f"Series: {series}")
logging.debug(f"Speaker: {speaker}")
logging.debug(f"Comment: {comment}")
# Making new file name
if name != album:
k = re.compile( "%s. (.+)" % (album) )
pname=name
if k.match(name):
pname = k.search( str(name) ).group(1)
name = "%s - %s" % (album, pname)
if series:
k = re.compile( "%s.? (.+)" % (series) )
pname=name
if k.match(name):
pname = k.search( str(name) ).group(1)
filename = "%s - %s. %s" % (author, series, pname)
else:
filename = "%s - %s" % (author, name)
if speaker:
filename = filename + " [%s]" % (speaker)
if comment:
filename = filename + " (%s)" % (comment)
filename=filename+".m4b"
logging.debug(f"Filename: {filename}")
return filename
for book in args.filenames:
AUTHOR = unicodedata.normalize('NFC', args.author ) if args.author else ''
ALBUM = unicodedata.normalize('NFC', args.album ) if args.album else ''
TITLE = unicodedata.normalize('NFC', args.title ) if args.title else ''
SPEAKER = unicodedata.normalize('NFC', args.speaker) if args.speaker else ''
SERIES = unicodedata.normalize('NFC', args.series ) if args.series else ''
COMMENT = unicodedata.normalize('NFC', args.comment) if args.comment else ''
logging.debug("AUTHOR : -=["+ str(AUTHOR)+"]=-")
logging.debug("ALBUM : -=["+ str(ALBUM)+"]=-")
logging.debug("TITLE : -=["+ str(TITLE)+"]=-")
logging.debug("SPEAKER : -=["+ str(SPEAKER)+"]=-")
logging.debug("SERIES : -=["+ str(SERIES)+"]=-")
logging.debug("COMMENT : -=["+ str(COMMENT)+"]=-")
logging.debug("MOVE : -=["+ str(MOVE)+"]=-")
logging.debug("RENAME : -=["+ str(RENAME)+"]=-")
logging.debug("DRYRUN : -=["+ str(DRYRUN)+"]=-")
logging.debug("VERBOSE : -=["+ str(args.verbose)+"]=-")
logging.debug("DEBUG : -=["+ str(args.debug)+"]=-")
audio = MP4(book)
logging.warning( f"Processing {book}" )
if AUTHOR:
logging.warning("Set Author to: %s" % AUTHOR)
audio["\xa9ART"] = [AUTHOR]
if TITLE:
logging.warning("Set Title to: %s" % TITLE)
audio["\xa9nam"] = [TITLE]
audio["\xa9alb"] = [TITLE]
if ALBUM:
if ALBUM == "-":
ALBUM = ""
logging.warning("ReSet Album")
audio["\xa9alb"] = ""
else:
logging.warning("Set Album to: %s" % ALBUM)
audio["\xa9alb"] = [ALBUM]
if SERIES:
if SERIES == "-":
SERIES = ""
logging.warning("ReSet Series")
audio["tvsh"] = ""
else:
logging.warning("Set Series name to: %s" % SERIES)
audio["tvsh"] = [SERIES]
if SPEAKER:
if SPEAKER == "-":
SPEAKER = ''
logging.warning("ReSet Speaker")
audio["aART"] = ''
audio['\xa9wrt'] = ''
else:
logging.warning("Set Speaker name to: %s" % SPEAKER)
audio["aART"] = [SPEAKER]
audio['\xa9wrt'] = [SPEAKER]
else:
#try to get speaker from file name
r=re.compile('\\[(.*)\\]')
p = r.search( book )
if p:
S=p.groups(1)
logging.warning("Set Speaker name to: %s" % str(S[0]))
audio["aART"] = [str(S[0])]
audio['\xa9wrt'] = [str(S[0])]
if COMMENT:
if COMMENT == "-":
COMMENT = ''
logging.warning("ReSet Comment")
audio["\xa9cmt"] = ''
else:
logging.warning("Set Comment to: %s" % COMMENT)
audio["\xa9cmt"] = [COMMENT]
else:
#try to get comment from file name
r=re.compile('\\((.*)\\)')
p = r.search( book )
logging.debug(f"geting comment from file name" )
if p:
S=p.groups(1)
logging.warning("Set Comment to: %s" % str(S[0]))
audio["\xa9cmt"] = [str(S[0])]
if not DRYRUN:
logging.debug("Saving data to AudioBook")
audio.save()
else:
logging.warning("DryRun option Set. do not storing data to audioBook")
if RENAME or MOVE:
tags=audio.tags
filename=mkfilename(tags)
if RENAME and not MOVE:
if not DRYRUN:
logging.info(f"Rename {book} to {filename}")
if (unicodedata.normalize('NFC', book) == unicodedata.normalize('NFC', filename)):
logging.error(f"No rename required for {filename}")
elif not os.path.isfile(filename):
shutil.move(book, filename)
else:
logging.error(f"Audiobook already exist:{ filename}")
sys.exit(98)
# todo add change comment "+1" and try again. no mere than 10 iteraction
else:
logging.warning(f"DryRun option Set. Do not renaming {book} to {filename}")
elif MOVE:
DIR=mkpath(tags)
if not os.path.isdir(DIR):
try:
if not DRYRUN:
logging.info(f"Create directory {DIR}")
os.makedirs(DIR)
else:
logging.warning(f"DryRun option Set. Do not create directory {DIR}")
except OSError as error:
logging.error(error)
sys.exit(99)
if not DRYRUN:
logging.info(f"Move {filename} to {DIR}/{filename}")
if not os.path.isfile(DIR +"/"+ filename):
shutil.move(book, DIR +"/"+ filename)
else:
logging.error(f"Audiobook already exist: {DIR}/{filename}")
sys.exit(98)
else:
logging.warning(f"DryRun option Set. Do not move {filename} to {DIR}/{filename}")
logging.warning("Done")
print("")