-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmetadata.py
102 lines (77 loc) · 2.62 KB
/
metadata.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
# Copyright (c) 2023, Nathan Hansen
# All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import os
import ffmpeg
import mutagen
def read_metadata(path):
if not os.path.isfile(path):
return [0, "Unknown", None]
try:
file = mutagen.File(path)
except mutagen.mp3.HeaderNotFoundError:
return [0, "Unknown", None]
tags = file.tags
duration = file.info.length
genre = "Unknown"
year = None
for k in tags.keys():
if "tcon" in k.lower():
# TCON is an official, recognised tag representing genre
genre = tags[k]
if "year" in k.lower():
# Year is not an official tag and is stored as TXXX:Year as a custom entry
year = tags[k]
return [duration, genre, year]
def check_normalized(path):
try:
tags = mutagen.File(path).tags
except (mutagen.mp3.HeaderNotFoundError, FileNotFoundError):
return False
for k in tags.keys():
if "norm" in k.lower():
# State is stored as a string
return tags[k] == "True"
return False
def set_normalized(basepath, songname, state):
if songname is None:
original_name = basepath
else:
original_name = os.path.join(basepath, songname)
tmp_name = original_name.split(".")
tmp_name = ".".join([tmp_name[0] + "_TMP"] + tmp_name[1:])
song = ffmpeg.input(original_name)
out = ffmpeg.output(
song,
tmp_name,
acodec="copy",
metadata=f"Norm={state}",
)
ffmpeg.run(out, quiet=True, overwrite_output=True)
os.replace(tmp_name, original_name)
def write_metadata(basepath, songname, genre, year):
original_name = os.path.join(basepath, songname)
tmp_name = original_name.split(".")
tmp_name = ".".join([tmp_name[0] + "_TMP"] + tmp_name[1:])
song = ffmpeg.input(original_name)
out = ffmpeg.output(
song,
tmp_name,
acodec="copy",
**{
"metadata": f"Year={year}",
"metadata:": f"Genre={genre}",
},
)
out = ffmpeg.overwrite_output(out)
ffmpeg.run(out, quiet=True)
os.replace(tmp_name, original_name)
if __name__ == "__main__":
folder = "D:\\Songs\\Meh"
songs = os.listdir(folder)
slen = len(songs)
for i, s in enumerate(songs):
if i % (slen // 10) == 0:
print(f"Progress: {i+1}/{slen} ({(i+1)/slen:.1%})")
set_normalized(folder, s, False)