-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
288 lines (229 loc) · 8.87 KB
/
utils.py
File metadata and controls
288 lines (229 loc) · 8.87 KB
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
from mutagen.id3 import ID3, TIT2, TPE1, TALB, TDRC, TCON, TRCK, TPOS, TCOM, TPE2, COMM, USLT, TBPM, TSRC, APIC
from mutagen.flac import FLAC, Picture
from mutagen.oggvorbis import OggVorbis
from mutagen.mp4 import MP4, MP4Cover
from mutagen.wave import WAVE
from mutagen.oggopus import OggOpus
from mutagen.asf import ASF, ASFByteArrayAttribute
from mutagen.aiff import AIFF
from base64 import b64encode
import os
import subprocess
import struct
def printHelp():
print("""
Manual mode:
Select a single file or a folder of audio files, then fill in each
metadata field (title, artist, album, year, genre, etc.) by hand.
In album/batch mode shared fields are entered once and only the
title and track number are prompted per file.
You can optionally convert files to another format (requires FFmpeg).
Automatic mode:
Search TheAudioDB by artist and album name. Choose whether you are
tagging a single song or a full album. The retrieved metadata
(including cover art) is previewed before being applied.
For albums, each file is matched to a track from the tracklist.
Supported formats:
MP3, FLAC, OGG, Opus, MP4, M4A, M4B, M4P, M4V, 3GP, ASF, WMA,
WMV, AIF, AIFF, WAV
Notes:
- Cover art must be a JPEG (.jpg) file.
- Lyrics are read from a plain text file.
- WAV tagging and format conversion require FFmpeg on PATH.
""")
_EXTENSION_HANDLERS = {
".mp3": lambda p, m: setID3Metadata(p, m),
".flac": lambda p, m: setFlacMetadata(p, m),
".ogg": lambda p, m: setOggMetadata(p, m),
".opus": lambda p, m: setOpusMetadata(p, m),
".wav": lambda p, m: setWavMetadata(p, m),
".aif": lambda p, m: setAIFMetadata(p, m),
".aiff": lambda p, m: setAIFMetadata(p, m),
".asf": lambda p, m: setASFMetadata(p, m),
".wma": lambda p, m: setASFMetadata(p, m),
".wmv": lambda p, m: setASFMetadata(p, m),
".mp4": lambda p, m: setMP4Metadata(p, m),
".m4a": lambda p, m: setMP4Metadata(p, m),
".m4b": lambda p, m: setMP4Metadata(p, m),
".m4p": lambda p, m: setMP4Metadata(p, m),
".m4v": lambda p, m: setMP4Metadata(p, m),
".3gp": lambda p, m: setMP4Metadata(p, m),
}
def setMetadata(extension, path, metadata):
handler = _EXTENSION_HANDLERS.get(extension)
if handler:
handler(path, metadata)
# --- ID3 (MP3, WAV, AIF/AIFF) ---
def setID3Tags(audio_file, metadata):
if "title" in metadata:
audio_file["TIT2"] = TIT2(encoding=3, text=metadata["title"])
if "artist" in metadata:
audio_file["TPE1"] = TPE1(encoding=3, text=metadata["artist"])
if "album" in metadata:
audio_file["TALB"] = TALB(encoding=3, text=metadata["album"])
if "year" in metadata:
audio_file["TDRC"] = TDRC(encoding=3, text=str(metadata["year"]))
if "genre" in metadata:
audio_file["TCON"] = TCON(encoding=3, text=metadata["genre"])
if "track" in metadata or "tracks" in metadata:
track = metadata.get("track", "")
total = metadata.get("tracks", "")
audio_file["TRCK"] = TRCK(encoding=3, text=f"{track}/{total}".strip("/"))
if "disk" in metadata or "disks" in metadata:
disk = metadata.get("disk", "")
total = metadata.get("disks", "")
audio_file["TPOS"] = TPOS(encoding=3, text=f"{disk}/{total}".strip("/"))
if "compositor" in metadata:
audio_file["TCOM"] = TCOM(encoding=3, text=metadata["compositor"])
if "albumArtist" in metadata:
audio_file["TPE2"] = TPE2(encoding=3, text=metadata["albumArtist"])
if "comments" in metadata:
audio_file["COMM"] = COMM(encoding=3, lang="eng", desc="desc", text=metadata["comments"])
if "lyrics" in metadata:
audio_file["USLT"] = USLT(encoding=3, lang="eng", desc="lyrics", text=metadata["lyrics"])
if "bpm" in metadata:
audio_file["TBPM"] = TBPM(encoding=3, text=str(metadata["bpm"]))
if "isrc" in metadata:
audio_file["TSRC"] = TSRC(encoding=3, text=metadata["isrc"])
# Cover art
if "image" in metadata and metadata["image"]:
with open(metadata["image"], "rb") as img:
audio_file["APIC"] = APIC(
encoding=3,
mime="image/jpeg",
type=3,
desc="Cover",
data=img.read(),
)
def setID3Metadata(path, metadata):
audio_file = ID3(path)
setID3Tags(audio_file, metadata)
audio_file.save(path)
def setWavMetadata(path, metadata):
# Rename temporarily, run through FFmpeg to get a WAV structure Mutagen can tag
pre_path = os.path.join(os.path.dirname(path), "pre_" + os.path.basename(path))
os.rename(path, pre_path)
touchWav(pre_path, path)
os.remove(pre_path)
audio = WAVE(path)
if audio.tags is None:
audio.add_tags()
audio.save()
setID3Tags(audio, metadata)
audio.save()
def setAIFMetadata(path, metadata):
audio_file = AIFF(path)
setID3Tags(audio_file, metadata)
audio_file.save(path)
def touchWav(inputPath, outputPath):
subprocess.run(["ffmpeg", "-i", inputPath, outputPath], check=True)
# --- Vorbis (FLAC, OGG, Opus) ---
simple_vorbis_map = {
"title": "TITLE",
"artist": "ARTIST",
"album": "ALBUM",
"year": "DATE",
"genre": "GENRE",
"isrc": "ISRC",
"track": "TRACKNUMBER",
"tracks": "TRACKTOTAL",
"disk": "DISKNUMBER",
"disks": "DISKTOTAL",
}
def setFlacMetadata(path, metadata):
audio = FLAC(path)
for key, vorbis_key in simple_vorbis_map.items():
if key in metadata and metadata[key]:
audio[vorbis_key] = str(metadata[key])
if "image" in metadata and metadata["image"]:
picture = Picture()
picture.type = 3
picture.mime = "image/jpeg"
with open(metadata["image"], "rb") as img:
picture.data = img.read()
audio.clear_pictures()
audio.add_picture(picture)
audio.save()
def setOggTags(oggFile, metadata):
if oggFile.tags is None:
oggFile.add_tags()
for key, vorbis_key in simple_vorbis_map.items():
if key in metadata and metadata[key]:
oggFile[vorbis_key] = str(metadata[key])
if "image" in metadata and metadata["image"]:
picture = Picture()
picture.type = 3
picture.mime = "image/jpeg"
with open(metadata["image"], "rb") as img:
picture.data = img.read()
oggFile["METADATA_BLOCK_PICTURE"] = [b64encode(picture.write()).decode("ascii")]
def setOggMetadata(path, metadata):
audio = OggVorbis(path)
setOggTags(audio, metadata)
audio.save()
def setOpusMetadata(path, metadata):
audio = OggOpus(path)
setOggTags(audio, metadata)
audio.save()
# --- MP4 (MP4, M4A, M4B, M4P, M4V, 3GP) ---
simple_mp4_map = {
"title": "\xa9nam",
"artist": "\xa9ART",
"album": "\xa9alb",
"year": "\xa9day",
"genre": "\xa9gen",
"track": "trkn",
"disk": "disk",
"compositor": "\xa9wrt",
"albumArtist": "aART",
"comments": "\xa9cmt",
"bpm": "tmpo",
"isrc": "\xa9isrc",
}
def setMP4Metadata(path, metadata):
audio = MP4(path)
for key, mp4_key in simple_mp4_map.items():
if key in metadata and metadata[key]:
if key == "track":
audio["trkn"] = [(int(metadata["track"]), int(metadata.get("tracks", 0)))]
elif key == "disk":
audio["disk"] = [(int(metadata["disk"]), int(metadata.get("disks", 0)))]
else:
audio[mp4_key] = [metadata[key]]
if "image" in metadata and metadata["image"]:
with open(metadata["image"], "rb") as img:
cover = MP4Cover(img.read(), imageformat=MP4Cover.FORMAT_JPEG)
audio["covr"] = [cover]
audio.save()
# --- ASF (ASF, WMA, WMV) ---
asf_map = {
"title": "Title",
"artist": "Author",
"album": "WM/AlbumTitle",
"genre": "WM/Genre",
"year": "WM/Year",
"compositor": "WM/Composer",
"albumArtist": "WM/AlbumArtist",
"comments": "Description",
"bpm": "WM/BeatsPerMinute",
"isrc": "WM/ISRC",
"track": "WM/TrackNumber",
}
def setASFMetadata(path, metadata):
audio = ASF(path)
for key, asf_key in asf_map.items():
if key in metadata and metadata[key]:
audio[asf_key] = metadata[key]
audio["WM/MediaClassPrimaryID"] = "{D1607DDE-7B67-4B88-9E0A-FB37E2049096}"
audio["WM/MediaClassSecondaryID"] = "{00000000-0000-0000-0000-000000000000}"
audio["WM/ContentType"] = "audio"
if "image" in metadata and metadata["image"]:
with open(metadata["image"], "rb") as img:
image_data = img.read()
type_byte = struct.pack("<b", 3)
size_bytes = struct.pack("<i", len(image_data))
mime_utf16 = "image/jpeg".encode("utf-16-le") + b"\x00\x00"
desc_utf16 = b"\x00\x00"
packed = type_byte + size_bytes + mime_utf16 + desc_utf16 + image_data
audio["WM/Picture"] = [ASFByteArrayAttribute(packed)]
audio.save()