-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
366 lines (288 loc) · 12.4 KB
/
app.py
File metadata and controls
366 lines (288 loc) · 12.4 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
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
import questionary
import os
import subprocess
import requests
import tempfile
from constants import (
ART, SINGLE, ALBUM, BATCH, PER_FILE,
info_list, info_list_labels, file_extensions_supported, metadata_by_file_extension, empty_info,
)
from utils import setMetadata, printHelp
CYAN = "\033[96m"
RESET = "\033[0m"
BASE_URL = "https://www.theaudiodb.com/api/v1/json/123"
_supported_tuple = tuple(file_extensions_supported)
_required_text = lambda s: bool(s and s.strip())
def cyan(text):
print(f"{CYAN}{text}{RESET}")
def convertFFMPEG(inputPath, outputPath):
command = ["ffmpeg", "-i", inputPath]
if outputPath.endswith(".3gp"):
command.extend(["-vn", "-c:a", "aac", "-b:a", "128k", "-f", "3gp"])
command.append(outputPath)
subprocess.run(command, check=True)
def validateJPGForCover(path):
return not path or path.lower().endswith(".jpg")
def selectFiles(path_to_data):
for _, _, files in os.walk(path_to_data):
supported = [f for f in files if f.endswith(_supported_tuple)]
selected = questionary.checkbox(
"Which files do you want to include?", qmark="?", choices=supported,
).ask()
return [os.path.abspath(os.path.join(path_to_data, f)) for f in selected]
return []
def buildTrackInfo(album_info, track, total_tracks, cover_path=None):
album = album_info or {}
info = empty_info.copy()
info["title"] = track.get("strTrack") or ""
info["artist"] = album.get("strArtist") or track.get("strArtist") or ""
info["album"] = album.get("strAlbum") or track.get("strAlbum") or ""
info["genre"] = album.get("strGenre") or track.get("strGenre") or ""
info["year"] = str(album.get("intYearReleased") or "")
info["track"] = str(track.get("intTrackNumber") or "")
info["tracks"] = str(total_tracks)
if cover_path:
info["image"] = cover_path
return info
# --- Manual process ---
def doProcessManualProcess():
mode = questionary.select(
"Are you modifying one or multiple files?", choices=[SINGLE, ALBUM],
).ask()
is_single = mode == SINGLE
def validatePathOrFile(path):
if is_single:
return os.path.isfile(path) and path.endswith(_supported_tuple)
return os.path.isdir(path)
path_to_data = questionary.path("Where is(are) the file(s)?", validate=validatePathOrFile).ask()
if is_single:
process = PER_FILE
files_to_modify = [os.path.abspath(path_to_data)]
else:
process = questionary.select(
"Do you want to modify all the files at the same time or you want to go one by one?",
choices=[BATCH, PER_FILE],
).ask()
files_to_modify = selectFiles(path_to_data)
convert = questionary.select(
"Do you want to convert the file(s) to another format? ( requires FFmpeg )",
choices=["Yes", "No"],
).ask()
new_format = None
if convert == "Yes":
new_format = questionary.select("Select the new format", choices=file_extensions_supported).ask()
info = empty_info.copy()
for idx, file_to_modify in enumerate(files_to_modify):
file_name, file_extension = os.path.splitext(file_to_modify)
if new_format is not None:
output_file_name = file_name + new_format
convertFFMPEG(file_to_modify, output_file_name)
file_to_modify = output_file_name
file_extension = new_format
cyan(f"* File: {file_to_modify}")
for i, field in enumerate(info_list):
is_per_title = field in ("title", "track") or (field == "disk" and info["disks"] and int(info["disks"]) > 1)
if process == BATCH and idx > 0 and not is_per_title:
continue
if field not in metadata_by_file_extension[file_extension]:
continue
if field == "image":
info[field] = questionary.path(info_list_labels[i], validate=validateJPGForCover).ask()
elif field == "lyrics":
info[field] = questionary.path(info_list_labels[i]).ask()
else:
info[field] = questionary.autocomplete(
info_list_labels[i], qmark="?",
choices=[file_to_modify] if field == "title" else [info[field]],
).ask()
setMetadata(file_extension, file_to_modify, info)
cyan("* All done!")
# --- Automatic process (TheAudioDB) ---
def getDiscography(artist):
response = requests.get(BASE_URL + "/discography.php", params={"s": artist})
response.raise_for_status()
data = response.json()
return data.get("album") or []
def getAlbumInfo(artist, album):
response = requests.get(BASE_URL + "/searchalbum.php", params={
"s": artist,
"a": album,
})
response.raise_for_status()
data = response.json()
if not data.get("album"):
return None
return data["album"][0]
def searchTrack(artist, track_name):
response = requests.get(BASE_URL + "/searchtrack.php", params={
"s": artist, "t": track_name,
})
response.raise_for_status()
data = response.json()
if not data.get("track"):
return None
return data["track"][0]
def getAlbumTracks(idAlbum):
response = requests.get(BASE_URL + "/track.php", params={"m": idAlbum})
response.raise_for_status()
return response.json()["track"]
def downloadCoverImage(url):
response = requests.get(url)
response.raise_for_status()
tmp = tempfile.NamedTemporaryFile(suffix=".jpg", delete=False)
tmp.write(response.content)
tmp.close()
return tmp.name
def doProcessAutomaticProcess():
album_or_song = questionary.select(
"Do you want to search for a song or an album?", choices=["Song", "Album"],
).ask()
artist = questionary.text("Artist", validate=_required_text).ask()
is_single = False
album_info = None
tracks = []
track_info = None
if album_or_song == "Song":
single_or_album = questionary.select(
"Is the song a single or part of an album?", choices=["Single", "Part of an album"],
).ask()
is_single = single_or_album == "Single"
if is_single:
track_name = questionary.text("Track", validate=_required_text).ask()
track_info = searchTrack(artist, track_name)
if not track_info:
cyan("No track found matching that criteria.")
return
# Try to get album info for cover art and extra metadata
if track_info.get("idAlbum"):
album_info = getAlbumInfo(
track_info.get("strArtist") or artist,
track_info.get("strAlbum") or "",
)
if album_info:
tracks = getAlbumTracks(album_info["idAlbum"])
else:
MANUAL_OPTION = "Type album name manually..."
discography = getDiscography(artist)
if discography:
album_choices = [
f"{a['strAlbum']} ({a['intYearReleased']})" for a in discography
]
album_choices.append(MANUAL_OPTION)
selected = questionary.select("Select an album", choices=album_choices).ask()
if selected == MANUAL_OPTION:
selected_album = questionary.text("Album", validate=_required_text).ask()
else:
selected_album = discography[album_choices.index(selected)]["strAlbum"]
else:
cyan("No albums found in discography. Enter the album name manually.")
selected_album = questionary.text("Album", validate=_required_text).ask()
album_info = getAlbumInfo(artist, selected_album)
if not album_info:
cyan("No album found matching that criteria.")
return
tracks = getAlbumTracks(album_info["idAlbum"])
if album_or_song == "Song":
track_name = questionary.text("Track", validate=_required_text).ask()
track_info = next(
(t for t in tracks if (t.get("strTrack") or "").lower() == track_name.lower()),
None,
)
if not track_info:
cyan("No track found matching that name in the album.")
return
# Preview retrieved data
if album_or_song == "Song":
cyan("--- Song info ---")
print(f' Title: {track_info.get("strTrack") or ""}')
print(f' Artist: {(album_info or {}).get("strArtist") or track_info.get("strArtist") or ""}')
print(f' Album: {(album_info or {}).get("strAlbum") or track_info.get("strAlbum") or ""}')
print(f' Year: {(album_info or {}).get("intYearReleased") or ""}')
print(f' Genre: {(album_info or {}).get("strGenre") or track_info.get("strGenre") or ""}')
print(f' Track: {track_info.get("intTrackNumber") or ""}')
print(f' Cover: {"Yes" if (album_info or {}).get("strAlbumThumb") else "No"}')
else:
cyan("--- Album info ---")
print(f' Artist: {album_info.get("strArtist") or ""}')
print(f' Album: {album_info.get("strAlbum") or ""}')
print(f' Year: {album_info.get("intYearReleased") or ""}')
print(f' Genre: {album_info.get("strGenre") or ""}')
print(f' Tracks: {len(tracks)}')
print(f' Cover: {"Yes" if album_info.get("strAlbumThumb") else "No"}')
cyan("--- Tracks ---")
for t in tracks:
print(f' {t["intTrackNumber"]}. {t["strTrack"]}')
if not questionary.confirm("Do you want to apply this data?").ask():
return
# Ask for files to modify
if album_or_song == "Song":
path_to_data = questionary.path(
"Where is the file?",
validate=lambda p: os.path.isfile(p) and p.endswith(_supported_tuple),
).ask()
files_to_modify = [os.path.abspath(path_to_data)]
else:
path_to_data = questionary.path("Where are the files?", validate=os.path.isdir).ask()
files_to_modify = selectFiles(path_to_data)
# Optional format conversion
convert = questionary.select(
"Do you want to convert the file(s) to another format? ( requires FFmpeg )",
choices=["Yes", "No"],
).ask()
new_format = None
if convert == "Yes":
new_format = questionary.select("Select the new format", choices=file_extensions_supported).ask()
# Download cover art
temp_image = None
if (album_info or {}).get("strAlbumThumb"):
temp_image = downloadCoverImage(album_info["strAlbumThumb"])
# Build metadata and apply
if album_or_song == "Song":
info = buildTrackInfo(album_info, track_info, len(tracks), temp_image)
file_to_modify = files_to_modify[0]
file_name, file_extension = os.path.splitext(file_to_modify)
if new_format is not None:
output_file = file_name + new_format
convertFFMPEG(file_to_modify, output_file)
file_to_modify = output_file
file_extension = new_format
cyan(f"* File: {file_to_modify}")
setMetadata(file_extension, file_to_modify, info)
else:
track_choices = [f"{t['intTrackNumber']}. {t['strTrack']}" for t in tracks]
for file_to_modify in files_to_modify:
file_name, file_extension = os.path.splitext(file_to_modify)
if new_format is not None:
output_file = file_name + new_format
convertFFMPEG(file_to_modify, output_file)
file_to_modify = output_file
file_extension = new_format
cyan(f"* File: {file_to_modify}")
selected = questionary.select(
f"Which track is '{os.path.basename(file_to_modify)}'?",
choices=track_choices,
).ask()
selected_track = tracks[track_choices.index(selected)]
info = buildTrackInfo(album_info, selected_track, len(tracks), temp_image)
setMetadata(file_extension, file_to_modify, info)
if temp_image:
os.remove(temp_image)
cyan("* All done!")
# --- Main ---
def doProcess():
curr_process_type = questionary.select(
"Do you want to introduce the data manually or to retrieve it from the internet(TheAudioDB)?",
choices=["Manual", "Automatic"],
).ask()
if curr_process_type == "Manual":
doProcessManualProcess()
else:
doProcessAutomaticProcess()
print(ART)
curr_process = None
while curr_process != "Quit":
curr_process = questionary.select("Menu", choices=["Start", "Help", "Quit"]).ask()
match curr_process:
case "Start": doProcess()
case "Help": printHelp()
case "Quit": exit()