-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFormatAudioFile.py
174 lines (140 loc) · 5.39 KB
/
FormatAudioFile.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
# Author: Alexander Senger
# Version: 0.0.3
import eyed3
import os
import sys
import time
import string
import argparse
import logging
logging.basicConfig(level=logging.ERROR)
# relative path of the default tracks folder of the folder where the program is
MUSIC_PATH = os.path.join(sys.path[0], "tracks")
# additional not needed string extensions at the end of the file title
appendix = [
" (Original Mix)",
" (Extended Mix)",
" (Extended)",
" (DJ Mix)"
]
fileExtensions = [
"mp3",
"flac",
"wav"
]
def reconstructDataOutOfFilename(fileString):
# remove first leading numbers and replace all underscores
tempString = fileString.lstrip(string.digits).replace("_", " ")
# detect the file extension
_, fileExtension = os.path.splitext(tempString)
# remove the file extension
tempString = tempString[:-len(fileExtension)]
# remove all hyphens
artistName, trackName = tempString.split(" - ")
# prepare the artistName
artistName = artistName.replace("-", "")
artistName = artistName.replace(" and ", "&")
artistName = artistName.replace(" Feat. ", " Ft. ")
artistName = artistName.replace(" feat. ", " ft. ")
artistName = artistName.lstrip(' ') # removes first white space
# prepare the trackName
for element in appendix:
if trackName.title().endswith(element):
trackName = trackName[:-(len(element))]
break
return artistName.title(), trackName.title()
def renameFile(artistName, trackName, fileString, newFileString):
# only rename the file if the filenames are unidentical
if fileString != newFileString:
src = MUSIC_PATH + os.sep + fileString
dst = MUSIC_PATH + os.sep + newFileString
print(f"[{fileString}] -> [{newFileString}]")
try:
os.rename(src, dst)
except OSError:
print(f'Error: File in use [{fileString}]')
# TODO: consider to check if one of the tags is valid and reconstruct the other part out of the filename
def examineFileString(artistNameTag, trackNameTag, fileString, audiofile):
if (artistNameTag and trackNameTag):
artistName = artistNameTag
trackName = trackNameTag
else:
artistName, trackName = reconstructDataOutOfFilename(fileString)
# check later on if it's .mp3 before writing it in tags
audiofile.tag.artist = artistName
audiofile.tag.title = trackName
audiofile.tag.save()
newFileString = f"{artistName} - {trackName}.mp3"
return artistName, trackName, newFileString
def getArtistNameAndTrackNameFromTag(audiofile):
if audiofile.tag.artist is None:
artistName = None
else:
artistName = audiofile.tag.artist.lstrip(' ') #remove first white space
if audiofile.tag.title is None:
trackName = None
else:
trackName = audiofile.tag.title.lstrip(' ') #remove first white space
for element in appendix:
if trackName.endswith(element):
trackName = trackName[:-(len(element))]
break
audiofile.tag.title = trackName
audiofile.tag.save()
return artistName, trackName
def adjustFile(audiofile, fileString):
# try to get data from tags
artistNameTag, trackNameTag = getArtistNameAndTrackNameFromTag(audiofile)
artistName, trackName, newFileString = examineFileString(artistNameTag, trackNameTag, fileString, audiofile)
renameFile(artistName, trackName, fileString, newFileString)
# read the command line argument and check if it's a dir path
# returns the newly selected path or the default path and creates the default folder if it's not existing
def getCommandLineDirectory():
parser = argparse.ArgumentParser()
parser.add_argument(
"-p","--path", help="Select the folder of the transforming tracks.", nargs=1, type=str)
args = parser.parse_args()
if args.path:
if os.path.isdir(args.path[0]) == False:
print("Error: Path is invalid.")
sys.exit()
else:
return args.path[0]
else:
if os.path.exists(MUSIC_PATH) == False:
try:
os.mkdir(MUSIC_PATH)
except OSError:
print(
f"Creation of the directory [{MUSIC_PATH}] failed. Program terminated.")
else:
print(f"Successfully created default track directory [{MUSIC_PATH}].\nYou can put your music files now in there and execute again. Program terminated.")
sys.exit()
return MUSIC_PATH
def findMusicFiles():
global MUSIC_PATH
MUSIC_PATH = getCommandLineDirectory()
# scan files in the directory
fileNameList = [f for f in os.listdir(
MUSIC_PATH) if os.path.isfile(os.path.join(MUSIC_PATH, f))]
if len(fileNameList) == 0:
print(f"No files in folder [{MUSIC_PATH}] found. Program terminated.")
sys.exit()
# endswith can be extended by e.g. (('.mp3', '.flac'))
musicFiles = [el for el in fileNameList if el.lower().endswith('.mp3')]
if len(musicFiles) == 0:
print(f"No music files in folder [{MUSIC_PATH}] found. Program terminated.")
sys.exit()
return musicFiles
def main():
musicFiles = findMusicFiles()
for musicFileString in musicFiles:
audiofile = eyed3.load(os.path.join(MUSIC_PATH, musicFileString))
# TODO: if musicFileString endswith .wav/.mp3/.flac
adjustFile(audiofile, musicFileString)
print('Done')
if __name__ == '__main__':
executionStartTime = time.time()
main()
executionEndTime = time.time()
print(f'Execution time: {executionEndTime - executionStartTime}s')