/
audio_conv.py
executable file
·342 lines (293 loc) · 10.6 KB
/
audio_conv.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
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
#!/usr/bin/python3
import argparse
import logging
import os
import shutil
import sys
import time
import datetime
from dateutil import parser as dateparse
from util import fileops, imageops
from util.converter import Converter
from util.cleankiller import CleanKiller
def time_remaining(completed, remaining, elapsed_time):
"""Returns the time estimated given the number of completed items,
remaining items and the time elasped so far.
Pass in total sizes of files for more accurate estimation.
"""
if completed == 0:
return 0
return remaining * (elapsed_time / float(completed))
def display_progress(count, total, remaining_time):
"""Displays a progress bar and and print the remaining time.
Moves the cursor up a line afterwards.
"""
bar_len = 32
filled = int(round(bar_len * count) / float(total))
bar = "[" + "#" * filled + " " * (bar_len - filled) + "]"
print(
"{} {:>6.1%} Time left: {}".format(
bar,
count / float(total),
time.strftime("%H:%M:%S", time.gmtime(remaining_time)),
)
)
print(u"\u001b[1A\u001b[2K", end="")
def parse_args(args):
parser = argparse.ArgumentParser(
description="Converts audio files using ffmpeg," " preserves dir structure.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
# Positional
parser.add_argument("indir", help="Input directory.")
parser.add_argument("outdir", help="Output directory.")
# Files
parser.add_argument(
"-i",
"--inexts",
type=str,
nargs="+",
default=["flac", "alac", "wav"],
help="File types to convert.",
)
parser.add_argument(
"-o",
"--outext",
type=str,
# required=True,
help="Target file type for conversion.",
)
# FFMEPG settings
parser.add_argument(
"-O",
"--options",
nargs=argparse.REMAINDER,
help="Options to pass to ffmpeg.",
)
# Other files
parser.add_argument(
"--copyexts",
type=str,
nargs="+",
default=["jpg", "jpeg", "png", "gif", "log", "cue"],
help="Copy other files (e.g. images) to new dir.",
)
parser.add_argument(
"-C",
"--nocopyexts",
action="store_true",
help="Prevent copying of other files.",
)
parser.add_argument(
"--convertimages",
type=str,
metavar="EXT",
help="Convert images to a new format.",
)
# Tags
parser.add_argument(
"--updatetags",
nargs="?",
const="",
help="Update the tags of existing files, "
"optionally modified after a certain date."
"Dates should be formatted as per ISO8601.",
)
parser.add_argument(
"-U",
"--updateonly",
action="store_true",
help="Only perform updating, not conversion.",
)
# Converter settings
parser.add_argument(
"-p", "--pretend", action="store_true", help="Perform no actions."
)
parser.add_argument(
"-t", "--threads", type=int, default=4, help="Maximum number of threads used."
)
parser.add_argument("-v", "--verbose", action="store_true", help="Increase output.")
args = parser.parse_args(args)
if not os.path.exists(args.indir):
parser.error("Input directory does not exist.")
if args.updatetags is not None:
if args.updatetags == "":
args.updatetags = datetime.datetime.min
else:
args.updatetags = dateparse.parse(args.updatetags)
if args.convertimages is not None:
args.convertimages = args.convertimages.lstrip(".")
return vars(args)
def setup_logger():
logger = logging.getLogger()
logger.setLevel(logging.INFO)
handler = logging.FileHandler("audio_conv.log", "w")
handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
logger.addHandler(handler)
logger.propagate = False
return logger
def gather_files(args):
"""Searches directories for matching files.
Returns the files for converting, updating and skipping.
"""
convfiles, updatefiles, skipfiles = [], [], []
for f in fileops.search_exts(args["indir"], args["inexts"]):
t = fileops.convert_path(f, args["indir"], args["outdir"])
t = os.path.splitext(t)[0] + os.extsep + args["outext"]
if os.path.exists(t):
moddate = datetime.datetime.fromtimestamp(os.path.getmtime(f))
if args["updatetags"] is not None and moddate >= args["updatetags"]:
updatefiles.append(f)
else:
if args["verbose"]:
print("Skipping:", f)
skipfiles.append(f)
else:
convfiles.append(f)
convfiles.sort(reverse=True) # Optimise for pop later
updatefiles.sort(reverse=True) # Optimise for pop later
return convfiles, updatefiles, skipfiles
def convert(infiles, args, logger, killer):
"""Takes input files for conversion.
Returns the number of failed, completed and copied files,
and the time taken to convert.
"""
options = []
if args["options"] is not None:
options.extend(args["options"])
converter = Converter(options, args["threads"])
start_time = time.time()
num_files = len(infiles)
size_files = fileops.total_size(infiles)
update_progress = True
while converter.num_converted() < num_files:
# Check current processes
if converter.check_processes() > 0:
print("Logging errors...")
converter.log_errors(logger)
# update_progress = True
if converter.can_add_process() and len(infiles) > 0:
inf = infiles.pop()
outf = fileops.convert_path(inf, args["indir"], args["outdir"])
outf = os.path.splitext(outf)[0] + (os.extsep + args["outext"])
converter.add_convert_process(inf, outf, pretend=args["pretend"])
update_progress = True
# Update the progress
if update_progress:
time_left = time_remaining(
converter.size_conv,
size_files - converter.size_conv,
time.time() - start_time,
)
display_progress(converter.num_converted(), num_files, time_left)
update_progress = False
# Sleep only if really waiting
elif not args["pretend"]:
time.sleep(0.05)
if killer.kill_now:
converter.kill_all()
print("Exiting...")
exit(1)
return converter.failed, converter.completed, time.time() - start_time
def update_tags(infiles, args, logger, killer):
"""Updates the tags of infiles.
Returns the number of successful updates and the time taken.
"""
converter = Converter(threads=args["threads"])
start_time = time.time()
num_files = len(infiles)
size_files = fileops.total_size(infiles)
update_progress = True
while converter.num_converted() < num_files:
# Check current processes
if converter.check_processes() > 0:
print("Logging errors...")
converter.log_errors(logger)
# update_progress = True
if converter.can_add_process() and len(infiles) > 0:
inf = infiles.pop()
outf = fileops.convert_path(inf, args["indir"], args["outdir"])
outf = os.path.splitext(outf)[0] + (os.extsep + args["outext"])
converter.add_update_process(inf, outf, pretend=args["pretend"])
update_progress = True
# Update the progress
if update_progress:
time_left = time_remaining(
converter.size_conv,
size_files - converter.size_conv,
time.time() - start_time,
)
display_progress(converter.num_converted(), num_files, time_left)
update_progress = False
# Sleep only if really waiting
elif not args["pretend"]:
time.sleep(0.05)
if killer.kill_now:
converter.kill_all()
print("Exiting...")
exit(1)
return converter.completed, time.time() - start_time
def copy_other_files(args):
"""Copies files from the input ot output directory,
preserving directory structures.
"""
copied = 0
if not args["nocopyexts"]:
copy_files = fileops.search_exts(args["indir"], args["copyexts"])
for f in copy_files:
is_image = imageops.is_image(f)
new_f = fileops.convert_path(f, args["indir"], args["outdir"])
# Need to check if converted image exists
if args["convertimages"] is not None and is_image:
new_f = os.path.splitext(new_f)[0] + os.extsep + args["convertimages"]
if os.path.exists(new_f):
if args["verbose"]:
print("Skipping other:", f)
elif args["convertimages"] is not None and is_image:
print("Converting image:", f)
if not args["pretend"]:
imageops.convert_image(f, new_f)
copied += 1
else:
print("Copying other:", f)
if not args["pretend"]:
shutil.copy2(f, new_f)
copied += 1
return copied
if __name__ == "__main__":
args = parse_args(sys.argv[1:])
logger = setup_logger()
killer = CleanKiller()
convfiles, updatefiles, skipfiles = gather_files(args)
num_files = len(convfiles) + len(updatefiles) + len(skipfiles)
convert_time, update_time = 0.0, 0.0
if not args["updateonly"]:
failed, completed, convert_time = convert(convfiles, args, logger, killer)
copied = copy_other_files(args)
print("")
updated, update_time = update_tags(updatefiles, args, logger, killer)
print("")
# Display end msg
print(
"Processed {} dirs, {} files in {:.2f} seconds.".format(
fileops.count_dirs(args["indir"]), num_files, convert_time + update_time
)
)
if not args["updateonly"]:
print(
"Convert: {} errors, {} skipped, {} converted.".format(
failed, num_files - (failed + completed), completed
)
)
if args["copyexts"]:
print("Copy: {} other files copied.".format(copied))
if updated > 0:
print(
"Update: Updated tags in {} files, skipped {} files.".format(
updated, len(skipfiles)
)
)
# Remove empty logs
logging.shutdown()
if os.stat("audio_conv.log").st_size == 0:
os.remove("audio_conv.log")