eyeD3 0.9.8a1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,61 @@
1
+ import sys
2
+ import binascii
3
+ from pathlib import Path
4
+
5
+ import eyed3.id3
6
+ import eyed3.plugins
7
+ from eyed3.utils.log import getLogger
8
+
9
+ log = getLogger(__name__)
10
+
11
+
12
+ class ExtractPlugin(eyed3.plugins.LoaderPlugin):
13
+ NAMES = ["extract"]
14
+ SUMMARY = "Extract tags from audio files."
15
+
16
+ def __init__(self, arg_parser):
17
+ super().__init__(arg_parser, cache_files=True, track_images=False)
18
+ self.arg_group.add_argument("-o", "--output-file",
19
+ help="The the tag is written to this file in native format.")
20
+ self.arg_group.add_argument("-H", "--hex", action="store_true",
21
+ help="Output hexadecimal format.")
22
+ self.arg_group.add_argument("--strip-padding", action="store_true",
23
+ help="Exclude tag padding, if any.")
24
+
25
+ def handleFile(self, f, *args, **kwargs):
26
+ super().handleFile(f)
27
+ if self.audio_file is None or self.audio_file.tag is None:
28
+ return
29
+
30
+ tag = self.audio_file.tag
31
+ if not isinstance(tag, eyed3.id3.Tag):
32
+ print("Only ID3 tags can be extracted currently.", file=sys.stderr)
33
+ return 1
34
+
35
+ with open(tag.file_info.name, "rb") as tag_file:
36
+ if tag.version[0] != 1:
37
+ # info.tag_size includes padding.
38
+ tag_data = tag_file.read(tag.file_info.tag_size)
39
+ if self.args.strip_padding and tag.file_info.tag_padding_size:
40
+ # --strip-padding
41
+ tag_data = tag_data[:-tag.file_info.tag_padding_size]
42
+ else:
43
+ # ID3 v1.x
44
+ tag_data = tag_file.read()[-128:]
45
+
46
+ if self.args.output_file:
47
+ # --output-file
48
+
49
+ if Path(tag.file_info.name).resolve() == Path(self.args.output_file).resolve():
50
+ print("Input file overwriting not allowed, choose a different -o/--output-file",
51
+ file=sys.stderr)
52
+ return 1
53
+
54
+ with open(self.args.output_file, "wb") as out_file:
55
+ out_file.write(tag_data)
56
+ else:
57
+ if self.args.hex:
58
+ # --hex
59
+ tag_data = str(binascii.hexlify(tag_data), "ascii")
60
+
61
+ print(tag_data)
eyed3/plugins/fixup.py ADDED
@@ -0,0 +1,631 @@
1
+ import os
2
+ from collections import defaultdict
3
+
4
+ from eyed3.id3 import ID3_V2_4
5
+ from eyed3.id3.tag import TagTemplate
6
+ from eyed3.plugins import LoaderPlugin
7
+ from eyed3.utils import art
8
+ from eyed3.utils.prompt import prompt
9
+ from eyed3.utils.console import printMsg, Style, Fore
10
+ from eyed3 import core
11
+
12
+ from eyed3.core import (ALBUM_TYPE_IDS, TXXX_ALBUM_TYPE, EP_MAX_SIZE_HINT,
13
+ LP_TYPE, EP_TYPE, COMP_TYPE, VARIOUS_TYPE, DEMO_TYPE,
14
+ LIVE_TYPE, SINGLE_TYPE, VARIOUS_ARTISTS)
15
+
16
+ NORMAL_FNAME_FORMAT = "${artist} - ${track:num} - ${title}"
17
+ VARIOUS_FNAME_FORMAT = "${track:num} - ${artist} - ${title}"
18
+ SINGLE_FNAME_FORMAT = "${artist} - ${title}"
19
+
20
+ NORMAL_DNAME_FORMAT = "${best_date:prefer_release} - ${album}"
21
+ LIVE_DNAME_FORMAT = "${best_date:prefer_recording} - ${album}"
22
+
23
+
24
+ def _printChecking(msg, end='\n'):
25
+ print(Style.BRIGHT + Fore.GREEN + "Checking" + Style.RESET_ALL + " %s" % msg, end=end)
26
+
27
+
28
+ def _fixCase(s):
29
+ if s:
30
+ fixed_values = []
31
+ for word in s.split():
32
+ fixed_values.append(word.capitalize())
33
+ return " ".join(fixed_values)
34
+ else:
35
+ return s
36
+
37
+
38
+ def dirDate(d):
39
+ s = str(d)
40
+ if "T" in s:
41
+ s = s.split("T")[0]
42
+ return s.replace('-', '.')
43
+
44
+
45
+ class FixupPlugin(LoaderPlugin):
46
+ NAMES = ["fixup"]
47
+ SUMMARY = "Performs various checks and fixes to directories of audio files."
48
+ DESCRIPTION = """
49
+ Operates on directories at a time, fixing each as a unit (album,
50
+ compilation, live set, etc.). All of these should have common dates,
51
+ for example but other characteristics may vary. The ``--type`` should be used
52
+ whenever possible, ``lp`` is the default.
53
+
54
+ The following test and fixes always apply:
55
+
56
+ 1. Every file will be given an ID3 tag if one is missing.
57
+ 2. Set ID3 v2.4.
58
+ 3. Set a consistent album name for all files in the directory.
59
+ 4. Set a consistent artist name for all files, unless the type is
60
+ ``various`` in which case the artist may vary (but must exist).
61
+ 5. Ensure each file has a title.
62
+ 6. Ensure each file has a track # and track total.
63
+ 7. Ensure all files have a release and original release date, unless the
64
+ type is ``live`` in which case the recording date is set.
65
+ 8. All ID3 frames of the following types are removed: USER, PRIV
66
+ 9. All ID3 files have TLEN (track length in ms) set (or updated).
67
+ 10. The album/dir type is set in the tag. Types of ``lp`` and ``various``
68
+ do not have this field set since the latter is the default and the
69
+ former can be determined during sync. In ID3 terms the value is in
70
+ TXXX (description: ``%(TXXX_ALBUM_TYPE)s``).
71
+ 11. Files are renamed as follows:
72
+ - Type ``various``: %(VARIOUS_FNAME_FORMAT)s
73
+ - Type ``single``: %(SINGLE_FNAME_FORMAT)s
74
+ - All other types: %(NORMAL_FNAME_FORMAT)s
75
+ - A rename template can be supplied in --file-rename-pattern
76
+ 12. Directories are renamed as follows:
77
+ - Type ``live``: %(LIVE_DNAME_FORMAT)s
78
+ - All other types: %(NORMAL_DNAME_FORMAT)s
79
+ - A rename template can be supplied in --dir-rename-pattern
80
+
81
+ Album types:
82
+
83
+ - ``lp``: A traditinal "album" of songs from a single artist.
84
+ No extra info is written to the tag since this is the default.
85
+ - ``ep``: A short collection of songs from a single artist. The string 'ep'
86
+ is written to the tag's ``%(TXXX_ALBUM_TYPE)s`` field.
87
+ - ``various``: A collection of songs from different artists. The string
88
+ 'various' is written to the tag's ``%(TXXX_ALBUM_TYPE)s`` field.
89
+ - ``live``: A collection of live recordings from a single artist. The string
90
+ 'live' is written to the tag's ``%(TXXX_ALBUM_TYPE)s`` field.
91
+ - ``compilation``: A collection of songs from various recordings by a single
92
+ artist. The string 'compilation' is written to the tag's
93
+ ``%(TXXX_ALBUM_TYPE)s`` field. Compilation dates, unlike other types, may
94
+ differ.
95
+ - ``demo``: A demo recording by a single artist. The string 'demo' is
96
+ written to the tag's ``%(TXXX_ALBUM_TYPE)s`` field.
97
+ - ``single``: A track that should no be associated with an album (even if
98
+ it has album metadata). The string 'single' is written to the tag's
99
+ ``%(TXXX_ALBUM_TYPE)s`` field.
100
+
101
+ """ % globals()
102
+
103
+ def __init__(self, arg_parser):
104
+ super(FixupPlugin, self).__init__(arg_parser, cache_files=True,
105
+ track_images=True)
106
+ g = self.arg_group
107
+ self._handled_one = False
108
+
109
+ g.add_argument("--type", choices=ALBUM_TYPE_IDS, dest="dir_type",
110
+ default=None, help=ARGS_HELP["--type"])
111
+ g.add_argument("--fix-case", action="store_true", dest="fix_case",
112
+ help=ARGS_HELP["--fix-case"])
113
+ g.add_argument("-n", "--dry-run", action="store_true", dest="dry_run",
114
+ help=ARGS_HELP["--dry-run"])
115
+ g.add_argument("--no-prompt", action="store_true", dest="no_prompt",
116
+ help=ARGS_HELP["--no-prompt"])
117
+ g.add_argument("--dotted-dates", action="store_true",
118
+ help=ARGS_HELP["--dotted-dates"])
119
+ g.add_argument("--file-rename-pattern", dest="file_rename_pattern",
120
+ help=ARGS_HELP["--file-rename-pattern"])
121
+ g.add_argument("--dir-rename-pattern", dest="dir_rename_pattern",
122
+ help=ARGS_HELP["--dir-rename-pattern"])
123
+ g.add_argument("--no-dir-rename", action="store_true",
124
+ help=ARGS_HELP["--no-dir-rename"])
125
+ self._curr_dir_type = None
126
+ self._dir_files_to_remove = set()
127
+
128
+ def _getOne(self, key, values, default=None, Type=str,
129
+ required=True):
130
+ values = set(values)
131
+ if None in values:
132
+ values.remove(None)
133
+
134
+ if len(values) != 1:
135
+ printMsg(
136
+ "Detected %s %s names%s" %
137
+ ("0" if len(values) == 0 else "multiple",
138
+ key,
139
+ "." if not values
140
+ else (":\n\t%s" % "\n\t".join([str(v) for v in values])),
141
+ ))
142
+
143
+ value = prompt("Enter %s" % key.title(), default=default,
144
+ type_=Type, required=required)
145
+ else:
146
+ value = values.pop()
147
+
148
+ return value
149
+
150
+ def _getDates(self, audio_files):
151
+ tags = [f.tag for f in audio_files if f.tag]
152
+
153
+ rel_dates = set([t.release_date for t in tags if t.release_date])
154
+ orel_dates = set([t.original_release_date for t in tags
155
+ if t.original_release_date])
156
+ rec_dates = set([t.recording_date for t in tags if t.recording_date])
157
+
158
+ release_date, original_release_date, recording_date = None, None, None
159
+
160
+ def reduceDate(type_str, dates_set, default_date=None):
161
+ if len(dates_set or []) != 1:
162
+ reduced = self._getOne(type_str, dates_set,
163
+ default=str(default_date) if default_date
164
+ else None,
165
+ Type=core.Date.parse)
166
+ else:
167
+ reduced = dates_set.pop()
168
+ return reduced
169
+
170
+ if (False not in [a.tag.album_type == LIVE_TYPE for a in audio_files] or
171
+ self._curr_dir_type == LIVE_TYPE):
172
+ # The recording date is most meaningful for live music.
173
+ recording_date = reduceDate("recording date",
174
+ rec_dates | orel_dates | rel_dates)
175
+ rec_dates = {recording_date}
176
+
177
+ # Want when these set if they may recording time.
178
+ orel_dates.difference_update(rec_dates)
179
+ rel_dates.difference_update(rec_dates)
180
+
181
+ if orel_dates:
182
+ original_release_date = reduceDate("original release date",
183
+ orel_dates | rel_dates)
184
+ orel_dates = {original_release_date}
185
+
186
+ if rel_dates | orel_dates:
187
+ release_date = reduceDate("release date",
188
+ rel_dates | orel_dates)
189
+ elif (False not in [a.tag.album_type == COMP_TYPE
190
+ for a in audio_files] or
191
+ self._curr_dir_type == COMP_TYPE):
192
+ # The release date is most meaningful for comps, other track dates
193
+ # may differ.
194
+ if len(rel_dates) != 1:
195
+ release_date = reduceDate("release date", rel_dates | orel_dates)
196
+ else:
197
+ release_date = list(rel_dates)[0]
198
+ else:
199
+ if len(orel_dates) != 1:
200
+ # The original release date is most meaningful for studio music.
201
+ original_release_date = reduceDate("original release date",
202
+ orel_dates | rel_dates | rec_dates)
203
+ orel_dates = {original_release_date}
204
+ else:
205
+ original_release_date = list(orel_dates)[0]
206
+
207
+ if len(rel_dates) != 1:
208
+ release_date = reduceDate("release date", rel_dates | orel_dates)
209
+ rel_dates = {release_date}
210
+ else:
211
+ release_date = list(rel_dates)[0]
212
+
213
+ if rec_dates.difference(orel_dates | rel_dates):
214
+ recording_date = reduceDate("recording date", rec_dates)
215
+
216
+ return release_date, original_release_date, recording_date
217
+
218
+ def _resolveArtistInfo(self, audio_files):
219
+ assert self._curr_dir_type != SINGLE_TYPE
220
+
221
+ tags = [f.tag for f in audio_files if f.tag]
222
+ artists = set([t.album_artist for t in tags if t.album_artist])
223
+
224
+ # There can be 0 or 1 album artist values.
225
+ album_artist = None
226
+ if len(artists) > 1:
227
+ album_artist = self._getOne("album artist", artists, required=False)
228
+ elif artists:
229
+ album_artist = artists.pop()
230
+
231
+ artists = list(set([t.artist for t in tags if t.artist]))
232
+
233
+ if len(artists) > 1:
234
+ # There can be more then 1 artist when VARIOUS_TYPE or
235
+ # album_artist != None.
236
+ if not album_artist and self._curr_dir_type != VARIOUS_TYPE:
237
+ if prompt("Multiple artist names exist, process directory as "
238
+ "various artists", default=True):
239
+ self._curr_dir_type = VARIOUS_TYPE
240
+ else:
241
+ artists = [self._getOne("artist", artists, required=True)]
242
+ elif (album_artist == VARIOUS_ARTISTS and
243
+ self._curr_dir_type != VARIOUS_TYPE):
244
+ self._curr_dir_type = VARIOUS_TYPE
245
+ elif len(artists) == 0:
246
+ artists = [self._getOne("artist", [], required=True)]
247
+
248
+ # Fix up artist and album artist discrepancies
249
+ if len(artists) == 1 and album_artist:
250
+ artist = artists[0]
251
+ if album_artist != artist:
252
+ print("When there is only one artist it should match the "
253
+ "album artist. Choices are: ")
254
+ for s in [artist, album_artist]:
255
+ print("\t%s" % s)
256
+ album_artist = prompt("Select common artist and album artist",
257
+ choices=[artist, album_artist])
258
+ artists = [album_artist]
259
+
260
+ if self.args.fix_case:
261
+ album_artist = _fixCase(album_artist)
262
+ artists = [_fixCase(a) for a in artists]
263
+ return album_artist, artists
264
+
265
+ def _getAlbum(self, audio_files):
266
+ tags = [f.tag for f in audio_files if f.tag]
267
+ albums = set([t.album for t in tags if t.album])
268
+ album_name = (albums.pop() if len(albums) == 1
269
+ else self._getOne("album", albums))
270
+ assert album_name
271
+ return album_name if not self.args.fix_case else _fixCase(album_name)
272
+
273
+ def _checkCoverArt(self, directory, audio_files):
274
+ valid_cover = False
275
+
276
+ # Check for cover file.
277
+ _printChecking("for cover art...")
278
+ for dimg in self._dir_images:
279
+ art_type = art.matchArtFile(dimg)
280
+ if art_type == art.FRONT_COVER:
281
+ dimg_name = os.path.basename(dimg)
282
+ print(f"\t{dimg_name}")
283
+ valid_cover = True
284
+
285
+ if not valid_cover:
286
+ # FIXME: move the logic out fixup and into art.
287
+ # Look for a cover in the tags.
288
+ for tag in [af.tag for af in audio_files if af.tag]:
289
+ if valid_cover:
290
+ # It could be set below...
291
+ break
292
+ for img in tag.images:
293
+ if img.picture_type == img.FRONT_COVER:
294
+ file_name = img.makeFileName("cover")
295
+ print("\tFound front cover in tag, writing '%s'" % file_name)
296
+ with open(os.path.join(directory, file_name), "wb") as img_file:
297
+ img_file.write(img.image_data)
298
+ img_file.close()
299
+ valid_cover = True
300
+
301
+ # TODO: force rename of cover file to single/consistent name (e.g. cover)
302
+
303
+ return valid_cover
304
+
305
+ def start(self, args, config):
306
+ import eyed3.utils.prompt
307
+ eyed3.utils.prompt.DISABLE_PROMPT = "exit" if args.no_prompt else None
308
+
309
+ super(FixupPlugin, self).start(args, config)
310
+
311
+ def handleFile(self, f, *args, **kwargs):
312
+ super(FixupPlugin, self).handleFile(f, *args, **kwargs)
313
+ if not self.audio_file and f not in self._dir_images:
314
+ self._dir_files_to_remove.add(f)
315
+
316
+ def handleDirectory(self, directory, _):
317
+ if not self._file_cache:
318
+ return
319
+
320
+ directory = os.path.abspath(directory)
321
+ print("\n" + Style.BRIGHT + Fore.YELLOW +
322
+ "Scanning directory%s %s" % (Style.RESET_ALL, directory))
323
+
324
+ def _path(af):
325
+ return af.path
326
+
327
+ self._handled_one = True
328
+
329
+ # Make sure all of the audio files has a tag.
330
+ for f in self._file_cache:
331
+ if f.tag is None:
332
+ f.initTag()
333
+
334
+ audio_files = sorted(list(self._file_cache), key=_path)
335
+
336
+ self._file_cache = []
337
+ edited_files = set()
338
+ self._curr_dir_type = self.args.dir_type
339
+ if self._curr_dir_type is None:
340
+ types = set([a.tag.album_type for a in audio_files])
341
+ if len(types) == 1:
342
+ self._curr_dir_type = types.pop()
343
+
344
+ # Check for corrections to LP, EP, COMP
345
+ if (self._curr_dir_type is None and
346
+ len(audio_files) < EP_MAX_SIZE_HINT):
347
+ # Do you want EP?
348
+ if False in [a.tag.album_type == EP_TYPE for a in audio_files]:
349
+ if prompt("Only %d audio files, process directory as an EP" %
350
+ len(audio_files),
351
+ default=True):
352
+ self._curr_dir_type = EP_TYPE
353
+ else:
354
+ self._curr_dir_type = EP_TYPE
355
+ elif (self._curr_dir_type in (EP_TYPE, DEMO_TYPE) and
356
+ len(audio_files) > EP_MAX_SIZE_HINT):
357
+ # Do you want LP?
358
+ if prompt("%d audio files is large for type %s, process "
359
+ "directory as an LP" % (len(audio_files),
360
+ self._curr_dir_type),
361
+ default=True):
362
+ self._curr_dir_type = LP_TYPE
363
+
364
+ last = defaultdict(lambda: None)
365
+
366
+ album_artist = None
367
+ artists = set()
368
+ album = None
369
+
370
+ if self._curr_dir_type != SINGLE_TYPE:
371
+ album_artist, artists = self._resolveArtistInfo(audio_files)
372
+ print(Fore.BLUE + "Album artist: " + Style.RESET_ALL +
373
+ (album_artist or ""))
374
+ print(Fore.BLUE + "Artist" + ("s" if len(artists) > 1 else "") +
375
+ ": " + Style.RESET_ALL + ", ".join(artists))
376
+
377
+ album = self._getAlbum(audio_files)
378
+ print(Fore.BLUE + "Album: " + Style.RESET_ALL + album)
379
+
380
+ rel_date, orel_date, rec_date = self._getDates(audio_files)
381
+ for what, d in [("Release", rel_date),
382
+ ("Original", orel_date),
383
+ ("Recording", rec_date)]:
384
+ print(f"{Fore.BLUE} {what} date: {Style.RESET_ALL} {d}")
385
+
386
+ num_audio_files = len(audio_files)
387
+ track_nums = set([f.tag.track_num[0] for f in audio_files])
388
+ fix_track_nums = set(range(1, num_audio_files + 1)) != track_nums
389
+ new_track_nums = []
390
+
391
+ dir_type = self._curr_dir_type
392
+ for f in sorted(audio_files, key=_path):
393
+ print(Style.BRIGHT + Fore.GREEN + "Checking" + Fore.RESET +
394
+ Style.BRIGHT + (" %s" % os.path.basename(f.path)) +
395
+ Style.RESET_ALL)
396
+
397
+ if not f.tag:
398
+ print("\tAdding new tag")
399
+ f.initTag()
400
+ edited_files.add(f)
401
+ tag = f.tag
402
+
403
+ if tag.version != ID3_V2_4:
404
+ print("\tConverting to ID3 v2.4")
405
+ tag.version = ID3_V2_4
406
+ edited_files.add(f)
407
+
408
+ if dir_type != SINGLE_TYPE and album_artist != tag.album_artist:
409
+ print("\tSetting album artist: %s" % album_artist)
410
+ tag.album_artist = album_artist
411
+ edited_files.add(f)
412
+
413
+ if not tag.artist and dir_type in (VARIOUS_TYPE, SINGLE_TYPE):
414
+ # Prompt artist
415
+ tag.artist = prompt("Artist name", default=last["artist"])
416
+ last["artist"] = tag.artist
417
+ elif len(artists) == 1 and tag.artist != artists[0]:
418
+ assert dir_type != SINGLE_TYPE
419
+ print("\tSetting artist: %s" % artists[0])
420
+ tag.artist = artists[0]
421
+ edited_files.add(f)
422
+
423
+ if tag.album != album and dir_type != SINGLE_TYPE:
424
+ print("\tSetting album: %s" % album)
425
+ tag.album = album
426
+ edited_files.add(f)
427
+
428
+ orig_title = tag.title
429
+ if not tag.title:
430
+ tag.title = prompt("Track title")
431
+ tag.title = tag.title.strip()
432
+ if self.args.fix_case:
433
+ tag.title = _fixCase(tag.title)
434
+ if orig_title != tag.title:
435
+ print("\tSetting title: %s" % tag.title)
436
+ edited_files.add(f)
437
+
438
+ if dir_type != SINGLE_TYPE:
439
+ # Track numbers
440
+ tnum, ttot = tag.track_num
441
+ update = False
442
+ if ttot != num_audio_files:
443
+ update = True
444
+ ttot = num_audio_files
445
+
446
+ if fix_track_nums or not (1 <= tnum <= num_audio_files):
447
+ tnum = None
448
+ while tnum is None:
449
+ tnum = int(prompt("Track #", type_=int))
450
+ if not (1 <= tnum <= num_audio_files):
451
+ print(Fore.RED + "Out of range: " + Fore.RESET +
452
+ "1 <= %d <= %d" % (tnum, num_audio_files))
453
+ tnum = None
454
+ elif tnum in new_track_nums:
455
+ print(Fore.RED + "Duplicate value: " + Fore.RESET +
456
+ str(tnum))
457
+ tnum = None
458
+ else:
459
+ update = True
460
+ new_track_nums.append(tnum)
461
+
462
+ if update:
463
+ tag.track_num = (tnum, ttot)
464
+ print("\tSetting track numbers: %s" % str(tag.track_num))
465
+ edited_files.add(f)
466
+ else:
467
+ # Singles
468
+ if tag.track_num != (None, None):
469
+ tag.track_num = (None, None)
470
+ edited_files.add(f)
471
+
472
+ if dir_type != SINGLE_TYPE:
473
+ # Dates
474
+ if rec_date and tag.recording_date != rec_date:
475
+ print("\tSetting %s date (%s)" %
476
+ ("recording", str(rec_date)))
477
+ tag.recording_date = rec_date
478
+ edited_files.add(f)
479
+ if rel_date and tag.release_date != rel_date:
480
+ print("\tSetting %s date (%s)" % ("release", str(rel_date)))
481
+ tag.release_date = rel_date
482
+ edited_files.add(f)
483
+ if orel_date and tag.original_release_date != orel_date:
484
+ print("\tSetting %s date (%s)" % ("original release",
485
+ str(orel_date)))
486
+ tag.original_release_date = orel_date
487
+ edited_files.add(f)
488
+
489
+ for frame in list(tag.frameiter(["USER", "PRIV"])):
490
+ print("\tRemoving %s frames: %s" %
491
+ (frame.id,
492
+ frame.owner_id if frame.id == b"PRIV" else frame.text))
493
+ tag.frame_set[frame.id].remove(frame)
494
+ edited_files.add(f)
495
+
496
+ # Add TLEN
497
+ tlen = tag.getTextFrame("TLEN")
498
+ if tlen is not None:
499
+ real_tlen_ms = f.info.time_secs * 1000
500
+ tlen_ms = float(tlen)
501
+ if tlen_ms != real_tlen_ms:
502
+ print("\tSetting TLEN (%d)" % real_tlen_ms)
503
+ tag.setTextFrame("TLEN", str(real_tlen_ms))
504
+ edited_files.add(f)
505
+
506
+ # Add custom album type if special and otherwise not able to be
507
+ # determined.
508
+ curr_type = tag.album_type
509
+ if curr_type != dir_type:
510
+ print("\tSetting %s = %s" % (TXXX_ALBUM_TYPE, dir_type))
511
+ tag.album_type = dir_type
512
+ edited_files.add(f)
513
+
514
+ try:
515
+ if not self._checkCoverArt(directory, audio_files):
516
+ if not prompt("Proceed without valid cover file", default=True):
517
+ return
518
+ finally:
519
+ self._dir_images = []
520
+
521
+ # Determine other changes, like file and/or directory renames
522
+ # so they can be reported before save confirmation.
523
+
524
+ # File renaming
525
+ file_renames = []
526
+ if self.args.file_rename_pattern:
527
+ format_str = self.args.file_rename_pattern
528
+ else:
529
+ if dir_type == SINGLE_TYPE:
530
+ format_str = SINGLE_FNAME_FORMAT
531
+ elif dir_type in (VARIOUS_TYPE, COMP_TYPE):
532
+ format_str = VARIOUS_FNAME_FORMAT
533
+ else:
534
+ format_str = NORMAL_FNAME_FORMAT
535
+
536
+ for f in audio_files:
537
+ orig_name, orig_ext = os.path.splitext(os.path.basename(f.path))
538
+ new_name = TagTemplate(format_str).substitute(f.tag, zeropad=True)
539
+ if orig_name != new_name:
540
+ printMsg("Rename file to %s%s" % (new_name, orig_ext))
541
+ file_renames.append((f, new_name, orig_ext))
542
+
543
+ # Directory renaming
544
+ dir_rename = None
545
+ if not self.args.no_dir_rename and dir_type != SINGLE_TYPE:
546
+ if self.args.dir_rename_pattern:
547
+ dir_format = self.args.dir_rename_pattern
548
+ else:
549
+ if dir_type == LIVE_TYPE:
550
+ dir_format = LIVE_DNAME_FORMAT
551
+ else:
552
+ dir_format = NORMAL_DNAME_FORMAT
553
+ template = TagTemplate(dir_format,
554
+ dotted_dates=self.args.dotted_dates)
555
+
556
+ pref_dir = template.substitute(audio_files[0].tag, zeropad=True)
557
+ if os.path.basename(directory) != pref_dir:
558
+ new_dir = os.path.join(os.path.dirname(directory), pref_dir)
559
+ printMsg("Rename directory to %s" % new_dir)
560
+ dir_rename = (directory, new_dir)
561
+
562
+ # Cruft files to remove
563
+ file_removes = []
564
+ if self._dir_files_to_remove:
565
+ for f in self._dir_files_to_remove:
566
+ print("Remove file: " + os.path.basename(f))
567
+ file_removes.append(f)
568
+ self._dir_files_to_remove = set()
569
+
570
+ if not self.args.dry_run:
571
+ confirmed = False
572
+
573
+ if (edited_files or file_renames or dir_rename or file_removes):
574
+ confirmed = prompt("\nSave changes", default=True)
575
+
576
+ if confirmed:
577
+ for f in edited_files:
578
+ print("Saving %s" % os.path.basename(f.path))
579
+ f.tag.save(version=ID3_V2_4, preserve_file_time=True)
580
+
581
+ for f, new_name, orig_ext in file_renames:
582
+ printMsg("Renaming file to %s%s" % (new_name, orig_ext))
583
+ f.rename(new_name, preserve_file_time=True)
584
+
585
+ if file_removes:
586
+ for f in file_removes:
587
+ printMsg("Removing file %s" % os.path.basename(f))
588
+ os.remove(f)
589
+
590
+ if dir_rename:
591
+ printMsg("Renaming directory to %s" % dir_rename[1])
592
+ s = os.stat(dir_rename[0])
593
+ os.rename(dir_rename[0], dir_rename[1])
594
+ # With a rename use the origianl access time
595
+ os.utime(dir_rename[1], (s.st_atime, s.st_atime))
596
+
597
+ else:
598
+ printMsg("\nNo changes made (run without -n/--dry-run)")
599
+
600
+ def handleDone(self):
601
+ if not self._handled_one:
602
+ printMsg("Nothing to do")
603
+
604
+
605
+ def _getTemplateKeys():
606
+ from eyed3.id3.tag import TagTemplate
607
+
608
+ keys = list(TagTemplate("")._makeMapping(None, False).keys())
609
+ keys.sort()
610
+ return ", ".join(["$%s" % v for v in keys])
611
+
612
+
613
+ ARGS_HELP = {
614
+ "--type": "How to treat each directory. The default is '%s', "
615
+ "although you may be prompted for an alternate choice "
616
+ "if the files look like another type." % ALBUM_TYPE_IDS[0],
617
+ "--fix-case": "Fix casing on each string field by capitalizing each "
618
+ "word.",
619
+ "--dry-run": "Only print the operations that would take place, but do "
620
+ "not execute them.",
621
+ "--no-prompt": "Exit if prompted.",
622
+ "--dotted-dates": "Separate date with '.' instead of '-' when naming "
623
+ "directories.",
624
+ "--file-rename-pattern": "Rename file (the extension is not affected) "
625
+ "based on data in the tag using substitution "
626
+ "variables: " + _getTemplateKeys(),
627
+ "--dir-rename-pattern": "Rename directory based on data in the tag "
628
+ "using substitution variables: " +
629
+ _getTemplateKeys(),
630
+ "--no-dir-rename": "Do not rename the directory.",
631
+ }