-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stagger.py
332 lines (289 loc) · 9.29 KB
/
Stagger.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
"""This moduler contains all methods and data for Stagger. Feel free to reuse it :3"""
# Initialization
import spotipy
import mutagen
from mutagen.flac import FLAC
from mutagen.mp3 import MP3
from mutagen.mp3 import EasyMP3 as EMP3
from mutagen.oggvorbis import OggVorbis as OGGV
import sys
# Map extra EasyID3 tags
for x in [
("year" , "TDRC"),
("track" , "TRCK"),
("initialkey" , "TKEY"),
("origdate" , "TDOR")
]:
EMP3.ID3.RegisterTextKey(x[0], x[1])
for x in [
"spotifyTrackID",
"spotifyAlbumID",
"itunesadvisory",
"tracktotal",
"disctotal"
]:
EMP3.ID3.RegisterTXXXKey(x, x)
# For reference - skipcq: PYL-W0105
"""
Predefined text mappings in EasyID3 / EMP3
"album" : "TALB"
"bpm" : "TBPM"
"title" : "TIT2"
"artist" : "TPE1"
"albumartist" : "TPE2"
"discnumber" : "TPOS"
"tracknumber" : "TRCK"
"isrc" : "TSRC"
"barcode" : "TXXX:BARCODE"
Predefined function mappings in EasyID3 / EMP3
"Genre" : genre_*
"Date" : date_*
"""
# Define class containing tag list
class tag:
"""Data values (list): `vorbis`, `id3`"""
vorbis = [
"title",
"track",
"tracktotal",
"album",
"year",
"origdate",
"albumartist",
"discnumber",
"disctotal",
"bpm",
"isrc",
"barcode",
"spotifyTrackID",
"spotifyAlbumID",
"artist",
"musicbrainz_albumtype",
"initialkey",
"itunesadvisory"
]
id3 = [
"TIT2",
"TRCK",
"TRCK",
"TALB",
"TDRC",
"TDAT",
"TPE2",
"TPOS",
"TXXX:TOTALDISCS",
"TBPM",
"TSRC",
"TXXX:BARCODE",
"TXXX:SPOTIFYTRACKID",
"TXXX:SPOTIFYALBUMID",
"TPE1",
"TXXX:MusicBrainz Album Type",
"TKEY"
]
# Find metadata in Spotify
def trackMeta(query: str,
auth_mgr: spotipy.SpotifyOAuth,
index: int = 0,
nameList: list = None) -> dict:
"""## Find metadata of `{query}` from spotify
### Args:
- query (str): String to search on Spotify
- auth_mgr (spotipy.SpotifyOAuth): Spotipy OAuthManager object
- index (int, optional): Check search item `{index}`. Defaults to 0.
- nameList (list): Contains a list of tag names orgainzed in a specific order.
See `idList` in this function to see format.
Defaults to a set meant for vorbis tags (inside function).
### Returns:
- dict: Contains search result of `{query}`
"""
__name__ = "Retrieve tag metadata"
# Initialize
spotify = spotipy.Spotify(auth_manager=auth_mgr)
# deepcode ignore change_to_is: Breaks code otherwise | skipcq: PTC-W0068
idList = tag.vorbis if nameList == None else nameList
# Build query
try:
result = spotify.search(q=query, type="track")
except KeyboardInterrupt:
print("Operation terminated by user")
print("\n======================================== >")
sys.exit()
except:
print("Network error - try again when you have a working internet connection")
print("\n======================================== >")
sys.exit()
resultTrack = spotify.track(track_id=result["tracks"]["items"][index]["id"])
resultAlbum = spotify.album(album_id=resultTrack["album"]["id"])
resultFeatures = spotify.audio_features(resultTrack["id"])[0]
# Build dict
trackMeta = {}
def trackAdd(key: str, data: list): trackMeta.update({key : data})
# Add simple ones
trackAdd(idList[0] , [resultTrack["name"]])
trackAdd(idList[1] , [str(resultTrack["track_number"])])
trackAdd(idList[2] , [str(resultTrack["album"]["total_tracks"])])
trackAdd(idList[3] , [resultTrack["album"]["name"]])
trackAdd(idList[4] , [resultAlbum["release_date"][0:4]])
trackAdd(idList[5] , [resultAlbum["release_date"]])
trackAdd(idList[6] , [resultTrack["album"]["artists"][0]["name"]])
trackAdd(idList[7] , [str(resultTrack["disc_number"])])
trackAdd(idList[8] , [str(resultAlbum["tracks"]["items"][-1]["disc_number"])])
trackAdd(idList[9] , [str(round(resultFeatures["tempo"]))])
trackAdd(idList[10], [resultTrack["external_ids"]["isrc"]])
trackAdd(idList[11], [resultAlbum["external_ids"]["upc"]])
trackAdd(idList[12], [resultTrack["id"]])
trackAdd(idList[13], [resultTrack["album"]["id"]])
# Do some manupilation to add a bit more complicated ones
## Artist
artist = [str(resultTrack["artists"][0]["name"])]
length = len(resultTrack["artists"])
if length > 1:
for x in range(1, length):
artist = artist + [resultTrack["artists"][x]["name"]]
trackAdd(idList[14], artist)
## Release type
trackType = str(resultTrack["album"]["album_type"])
if trackType == "single":
trackType = ["Single or EP"]
else:
trackType = [trackType.capitalize()]
trackAdd(idList[15], trackType)
## Key
### Map numbers to classical key
keyMap = {
"-1" : "",
"0" : "C",
"1" : "Db",
"2" : "D",
"3" : "Eb",
"4" : "E",
"5" : "F",
"6" : "Gb",
"7" : "G",
"8" : "Gb",
"9" : "A",
"10" : "Ab",
"11" : "B"
}
### Account for musical mode (Minor or Major)
modeMap = ["m", ""]
### Find classical key
key = str(resultFeatures["key"])
trackKey = keyMap[key] + modeMap[resultFeatures["mode"]]
### Map classical key to camelot
camelotMap = {
"C" : "8B",
"Db" : "3B",
"D" : "10B",
"Eb" : "5B",
"E" : "12B",
"F" : "7B",
"Gb" : "2B",
"G" : "9B",
"Ab" : "4B",
"A" : "11B",
"Bb" : "6B",
"B" : "1B",
"Cm" : "5A",
"Dbm" : "12A",
"Dm" : "7A",
"Ebm" : "2A",
"Em" : "9A",
"Fm" : "4A",
"Gbm" : "11A",
"Gm" : "6A",
"Abm" : "1A",
"Am" : "8A",
"Bbm" : "3A",
"Bm" : "10A"
}
# Append to dictionary
trackAdd(idList[16], [str(trackKey)] + [str(camelotMap[trackKey])])
## Explicitness
if resultTrack["explicit"]:
trackAdd(idList[17], ['1'])
elif not resultTrack["explicit"]:
trackAdd(idList[17], ['0'])
# Return Dictionary
return trackMeta
# Remove existing tags
def initTags(filename: str) -> None:
"""## Clears all tags from file `{filename}`
### Args:
- filename (str): Contains the name of the file
"""
__name__ = "Initialize Tags"
# deepcode ignore change_to_is: Breaks code otherwise | skipcq: PTC-W0068
file = mutagen.File(filename)
if (
type(file) is EMP3 or
type(file) is MP3
):
idList = tag.id3
file = MP3(filename)
elif (
type(file) is OGGV or
type(file) is FLAC
):
idList = tag.vorbis
if type(file) is OGGV:
file = OGGV(filename)
if type(file) is FLAC:
file = FLAC(filename)
for tagName in idList:
try:
del file[tagName]
except KeyError:
pass
# Check audio encoding type and return it
def findTypeFunc(audioFileName: str):
"""## Returns function for filetype or literal "UNSUPPORTED" if filetype not defined
### Args:
- audioFileName (str): Name of the file we need to check
### Returns (One Of):
- function: Returns function compatible with given file name
- "UNSUPPORTED": Returns this literal only if no compatible function for
`{audioFileName}` was found
"""
__name__ = "Find file type"
try:
try:
filetype = type(mutagen.File(audioFileName))
except:
raise UnboundLocalError
if filetype == FLAC:
fileFunc = FLAC(audioFileName)
print("Type: FLAC")
elif filetype == OGGV:
fileFunc = OGGV(audioFileName)
print("Type: OGG Vorbis")
elif filetype == MP3:
fileFunc = EMP3(audioFileName)
print("Type: MP3")
# deepcode ignore change_to_is: Breaks code otherwise | skipcq: PTC-W0068
if fileFunc != None: #
return fileFunc
return "UNSUPPORTED"
except UnboundLocalError:
print("Type: Undefined / Non-audio")
return "UNSUPPORTED"
# Define a function to make it simpler to add tags
def addTag(tagName : str, tagData : list, file: FLAC | OGGV | EMP3):
__name__ = "Add Tag"
try:
file[tagName] = ""
except KeyError:
pass
if type(file) is FLAC or type(file) is OGGV:
file.pop(tagName)
file.update({tagName: tagData})
elif type(file) is EMP3:
if tagName == "track":
tagName = "tracknumber"
file[tagName] = tagData
elif tagName == "track":
tagName = "tracknumber"
file[tagName] = tagData
else:
file[tagName] = tagData