-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfileFunctions.py
More file actions
331 lines (257 loc) · 8.51 KB
/
fileFunctions.py
File metadata and controls
331 lines (257 loc) · 8.51 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
import csv
import os
import re
import subprocess as sp
import typing as tp
import sysFunctions as sf
def pathChecks(path: str) -> None:
"""
Performs correctness checks for the specified path.
path : str
Path to the specified folder.
Returns None.
"""
# check "path" argument type provided
if not isinstance(path, str):
raise TypeError('"path" must be a string ' +
f'("{type(path)}" was provided)!')
# check whether "path" exists
if not os.path.exists(path):
raise Exception(f'Specified "path" ("{path}") does not exist!')
return None
def dirCheck(path: str) -> None:
"""
Performs whether the specified path is a directory.
path : str
Path to the specified folder.
Returns None.
"""
# check path correctness
pathChecks(path)
# check whether "path" is a folder
if not os.path.isdir(path):
raise Exception(f'Specified "path" ("{path}") is not a folder!')
return None
def fileCheck(path: str) -> None:
"""
Performs whether the specified path is a file.
path : str
Path to the specified file.
Returns None.
"""
# check path correctness
pathChecks(path)
# check whether "path" is a file
if not os.path.isfile(path):
raise Exception(f'Specified "path" ("{path}") is not a file!')
return None
def listFiles(path: str, recursive: bool=False) -> \
tp.Tuple[tp.List[str], tp.List[str]]:
"""
Lists files in the specified folder.
path : str
Path to the specified folder.
recursive : bool
Specifies whether to list files recursively.
Defaults to False (do not check folders recursively).
Returns:
List of file names : List[str].
List of full path to the files : List[str].
"""
# check "recursive" argument type provided
if not isinstance(recursive, bool):
raise TypeError('"recursive" must be a boolean ' +
f'("{type(recursive)}" was provided)!')
fileName = [] # file names only
fullName = [] # file full names
if recursive is True: # list files in the dir and subdirs
for root, dirs, files in os.walk(path):
files.sort() # sort the files in a folder by name
for file in files:
fileName.append(file)
fullName.append(os.path.join(root, file))
else: # list files in the dir only
files = os.listdir(path)
files.sort() # sort the files in a folder by name
for file in files:
fullPath = os.path.join(path, file)
if os.path.isfile(fullPath):
fileName.append(file)
fullName.append(fullPath)
return fileName, fullName
def getMetadata(files: tp.List[str]) -> \
tp.Tuple[tp.List[str], tp.List[str], tp.List[str], tp.List[str]]:
"""
Retrieve metadata from the list of files.
files : List[str]
List of files with their full paths.
Returns:
List of Bitrate Types : List[str].
List of Bitrates (kbps) : List[str].
List of song titles : List[str].
List of song artists : List[str].
"""
fileInfoCmd = 'mediainfo' # file info command
sf.cmdInstalled(fileInfoCmd) # check if command is installed
bitrateType = []
kbps = []
title = []
artist = []
# keywords to find appropriate info
keyAudio = 'audio' # used to check if it is an audio
keyBitrateType = 'bit.rate mode'
keykbps = 'bit.rate'
keykbpsUnit = 'kb.s'
keyTitle = 'track name'
keyArtist = 'performer'
nNP = 0 # count not processed files
for file in files:
fileCheck(file) # check if the file exists
metadata = sp.run([fileInfoCmd, file], stdout=sp.PIPE) # get metadata
metadata = metadata.stdout.decode('utf-8')
# metadata output contains file name which can contain keywords that
# that the script looks for
metadata = metadata.replace(file, '')
if keyAudio not in metadata.lower(): # if not an audio file
nNP += 1
print(f'{(str(nNP)+":").ljust(5)} "{file}" does not contain' +
' an Audio Section!')
bitrateType.append('')
kbps.append('')
title.append('')
artist.append('')
else: # if an audio file
# get Audio section
audioMetadata = metadata[re.search(f'^{keyAudio}$', metadata,
flags=re.MULTILINE | re.IGNORECASE).start():]
# get bitrate mode
result = re.findall(rf'^.*{keyBitrateType}.*$', audioMetadata,
flags=re.MULTILINE | re.IGNORECASE)
if result != []:
result = result[0]
result = re.findall(r":.*", result)[0]
result = result[1:].strip()
bitrateType.append(result)
else:
bitrateType.append('')
# get kbps
result = re.findall(rf'^.*{keykbps}.*$', audioMetadata,
flags=re.MULTILINE | re.IGNORECASE)
# remove bitrate type results
recomp = re.compile(rf'^(?!{keyBitrateType})', flags=re.IGNORECASE)
result = list(filter(recomp.match, result))
del recomp
if result != []:
result = result[0]
result = re.findall(rf'\d+[ ,]?\d*[.,]?\d*(?= {keykbpsUnit}$)',
result)[0]
result = result.replace(' ', '')
kbps.append(result)
else:
kbps.append('')
# get track name
result = re.findall(rf'^{keyTitle} .*$', metadata,
flags=re.MULTILINE | re.IGNORECASE)
if result != []:
result = result[0]
result = re.findall(r'(?<=: ).*$', result,
flags=re.MULTILINE | re.IGNORECASE)[0]
title.append(result)
else:
title.append('')
# get artist
result = re.findall(rf'^{keyArtist}.*$', metadata,
flags=re.MULTILINE | re.IGNORECASE)
if result != []:
result = result[0]
result = re.findall(r'(?<=: ).*$', result,
flags=re.MULTILINE | re.IGNORECASE)[0]
artist.append(result)
else:
artist.append('')
return bitrateType, kbps, title, artist
def getFileSize(files: tp.List[str]) -> tp.List[int]:
"""
Get file size in bytes.
files : List[str]
List of files with their full paths.
Returns:
List of the file size in bytes : List[int].
"""
sizeBytes = []
for file in files:
sizeBytes.append(os.stat(file).st_size)
return sizeBytes
def getFileExtension(files: tp.List[str]) -> tp.List[str]:
"""
Get file extensions.
files : List[str]
List of files with their full paths.
Returns:
List of the file extensions : List[str].
"""
extensions = []
for file in files:
index = file.rfind('.') # search for the extension separator
if index > -1: # if no file extension found
ext = file[index+1:]
else:
ext = ''
extensions.append(ext)
return extensions
def writeData(rootFolder : str,
fullNames : tp.List[str],
fileNames : tp.List[str],
extensions : tp.List[str],
bitrateTypes : tp.List[str],
kbps : tp.List[str],
titles : tp.List[str],
artists : tp.List[str],
sizeBytes : tp.List[int],
folderOut : str) -> None:
"""
Write file data into a CSV file.
rootFolder : str
A root folder
fullNames : List[str]
List of files with their full paths.
fileNames : List[str]
List of file names.
extensions : List[str]
List of file extensions.
bitrateTypes : List[str]
List of Bitrate Types.
kbps : List[str]
List of Bitrates (kbps).
titles : List[str]
List of song titles.
artists : List[str]
List of song artists.
sizeBytes : List[int]
List of the file size in bytes.
folderOut : str
The folder to which save the output CSV file.
Returns None.
"""
outFileName = 'out' + sf.getTimeStamp() + '.csv'
# write data to the file
with open(os.path.join(folderOut, outFileName), mode='w') as outcsv:
writer = csv.writer(outcsv, dialect='excel')
# write a header
writer.writerow([f'Full Name ({rootFolder})', 'File Name', 'Extension',
'Bitrate Type', 'kb/s', 'Title', 'Artist',
'Size, bytes', 'File Name (no extension, new)',
'Title (new)', 'Artist (new)'])
for i in range(len(fileNames)):
row = [] # join info into a row
row.append(fullNames[i])
row.append(fileNames[i])
row.append(extensions[i])
row.append(bitrateTypes[i])
row.append(kbps[i])
row.append(titles[i])
row.append(artists[i])
row.append(sizeBytes[i])
row.extend(['']*3)
writer.writerow(row)
return None