Repository navigation
Expand file tree
/
Copy pathimport_export.py
More file actions
302 lines (271 loc) · 9.36 KB
/
Copy pathimport_export.py
File metadata and controls
302 lines (271 loc) · 9.36 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
import csv
import os
import datetime
import hashes
import hashlib
import json
import math
import string
import ffmpeg
from jsonschema import validate
with open(os.path.dirname(os.path.realpath(__file__)) + "/pony_schema.json") as f:
schema = json.load(f)
try:
with open(os.path.dirname(os.path.realpath(__file__)) + "/settings.json") as f:
config = json.load(f)
except:
config = {
"audio_paths": [],
"audio_hashes": {},
}
def write_config():
path = os.path.dirname(os.path.realpath(__file__)) + "/settings.json"
with open(path, "w") as f:
json.dump(config, f, indent=4)
return path
def import_from_labels(filename):
episode_data = {}
episode_data["label_name"] = os.path.splitext(os.path.basename(filename))[
0
].replace(" ", "_")
if episode_data["label_name"] not in hashes.friendly_names:
return None
episode_data["friendly_name"] = hashes.friendly_names[episode_data["label_name"]]
episode_data["last_modified"] = datetime.datetime.utcnow().isoformat()
labels = []
with open(filename, encoding="utf-8") as f:
for i in csv.reader(f, delimiter="\t"):
label = {}
label["start"] = float(i[0])
label["end"] = float(i[1])
label["character"] = i[2].split("_")[3]
label["mood"] = i[2].split("_")[4].lower().split(" ")
label["transcript"] = i[2].split("_")[6]
label["noise_level"] = i[2].split("_")[5].replace(" ", "").lower()
if label["noise_level"] == "":
label["noise_level"] = "clean"
label["reviewed"] = False
labels.append(label)
episode_data["labels"] = labels
return episode_data
def import_from_json(filename):
with open(filename, encoding="utf-8") as f:
episode_data = json.load(f)
return episode_data
def check_progress(filename):
episode_data = import_from_json(filename)
a = 0
b = len(episode_data["labels"])
for l in episode_data["labels"]:
if l["reviewed"] == True:
a += 1
if a == b:
return 100
else:
return int((a / b) * 99)
def generate_label_filename(l):
if l["noise_level"] == "noisy":
noise = "Noisy"
elif l["noise_level"] == "verynoisy":
noise = "Very Noisy"
else:
noise = ""
hour = int(math.floor(round(l["start"]) / 3600))
minute = int(math.floor(round(l["start"]) / 60 % 60))
second = int(math.floor(round(l["start"]) % 60))
name = (
"{0:02d}".format(hour)
+ "_"
+ "{0:02d}".format(minute)
+ "_"
+ "{0:02d}".format(second)
+ "_"
+ l["character"]
+ "_"
+ string.capwords(" ".join(l["mood"]))
+ "_"
+ noise
+ "_"
+ l["transcript"]
+ "\n"
)
return name
def generate_clean_filename(l, label_name):
name = generate_label_filename(l)
split = name.split(sep="_")
for i, s in enumerate(split):
split[i] = "".join(x for x in s if x.isalnum())
split[i] = split[i][:32]
name = "".join(x for x in label_name if x.isalnum()) + "_" + "_".join(split).lower()
return name
def export_to_labels(episode_data, character_filter=None, source_filter=None):
dirpath = os.path.dirname(os.path.realpath(__file__)) + "/exported_labels/"
try:
os.makedirs(dirpath)
except:
pass
if source_filter != None:
fullpath = dirpath + episode_data["label_name"] + "_" + source_filter + ".txt"
else:
fullpath = dirpath + episode_data["label_name"] + ".txt"
with open(fullpath, "w", encoding="utf-8") as f:
missing_warning = False
for l in episode_data["labels"]:
if character_filter != None and l["character"] != character_filter:
continue
if source_filter != None and "ideal_source" not in l:
if not missing_warning:
print("Warning: missing source(s) in " + episode_data["label_name"])
missing_warning = True
continue
if source_filter != None and l["ideal_source"] != source_filter:
continue
f.write(
"{:.6f}".format(l["start"])
+ "\t"
+ "{:.6f}".format(l["end"])
+ "\t"
+ generate_label_filename(l)
)
return fullpath
def find_audio_path(episode_name):
original_path = ""
izo_path = ""
unmix_path = ""
original_hash = hashes.original_hashes[episode_name]
izo_hash = hashes.izo_hashes[episode_name]
unmix_hash = hashes.unmix_hashes[episode_name]
for k, v in config["audio_hashes"].items():
if v == original_hash:
original_path = k
if v == izo_hash:
izo_path = k
if v == unmix_hash:
unmix_path = k
return (original_path, izo_path, unmix_path)
def split_by_pony(
episode_data,
character_filter=None,
mood_filter=[],
allow_questions=True,
default_source="izo",
):
metadata = []
dirpath = os.path.dirname(os.path.realpath(__file__)) + "/exported_clips/wavs/"
try:
os.makedirs(dirpath)
except:
pass
original_path, izo_path, unmix_path = find_audio_path(episode_data["label_name"])
for l in episode_data["labels"]:
if character_filter != None and l["character"] != character_filter:
continue
if l["mood"][0] not in mood_filter:
continue
if not allow_questions and "?" in l["transcript"]:
continue
if "ideal_source" in l:
source = l["ideal_source"]
else:
source = default_source
if source == "original":
inputfile = original_path
elif source == "izo":
inputfile = izo_path
elif source == "unmix":
inputfile = unmix_path
filename = generate_clean_filename(l, episode_data["label_name"])
ffmpeg.input(inputfile, ss=l["start"], t=l["end"] - l["start"]).output(
dirpath + filename + ".wav", ar="22050"
).overwrite_output().run()
metadata.append(filename + "|" + l["transcript"] + "|" + l["transcript"])
return metadata
def export_to_json(episode_data):
dirpath = os.path.dirname(os.path.realpath(__file__)) + "/saved_changes/"
try:
os.makedirs(dirpath)
except:
pass
fullpath = dirpath + episode_data["label_name"] + ".json"
with open(fullpath, "w", encoding="utf-8") as f:
json.dump(episode_data, f, indent=4, ensure_ascii=False)
return fullpath
def hash_audio_files(queue):
new_audio = 0
queue.put("Hashing audio files...")
for p in config["audio_paths"]:
for r, _, f in os.walk(p):
for file in f:
if ".flac" in file:
if os.path.join(r, file) in config["audio_hashes"]:
continue
hasher = hashlib.sha1()
with open(os.path.join(r, file), "rb") as openfile:
readfile = openfile.read()
hasher.update(readfile)
hash = hasher.hexdigest()
config["audio_hashes"][os.path.join(r, file)] = hash
queue.put("Hashed " + file)
new_audio += 1
queue.put("Done! Found " + str(new_audio) + " new audio file(s)")
write_config()
queue.put("msgdone")
def get_chars_and_moods(filename):
chars = set()
moods = set()
episode_data = import_from_json(filename)
for l in episode_data["labels"]:
chars.add(l["character"])
for m in l["mood"]:
moods.add(m)
return chars, moods
def episode_format(name):
if name.startswith("fim_s"):
return "s" + str(int(name[5:7])) + "e" + str(int(name[8:10]))
else:
return name.replace("_", "")
def format_name(
name_format,
episode,
number,
seconds,
character,
moods,
transcript,
noise_level,
audio_source,
extension,
filter_reserved,
filter_space,
):
# Prepare metadata
if noise_level == "noisy":
noise = "Noisy"
elif noise_level == "verynoisy":
noise = "Very Noisy"
else:
noise = ""
hour = int(math.floor(round(seconds) / 3600))
minute = int(math.floor(round(seconds) / 60 % 60))
second = int(math.floor(round(seconds) % 60))
# Format output string
output = name_format
output = output.replace("{h}", "{0:02d}".format(hour))
output = output.replace("{m}", "{0:02d}".format(minute))
output = output.replace("{s}", "{0:02d}".format(second))
output = output.replace("{xs}", "{0:.3f}".format(seconds))
output = output.replace("{num}", str(number))
output = output.replace("{ep}", episode_format(episode))
output = output.replace("{c}", character)
output = output.replace("{md}", string.capwords(" ".join(moods)))
output = output.replace("{md0}", string.capwords(moods[0]))
output = output.replace("{t}", transcript)
output = output.replace("{nl}", noise)
output = output.replace("{src}", audio_source)
if filter_reserved:
reserved = ["<", ">", ":", '"', "/", "\\", "|", "?", "*", "\0"]
for r in reserved:
output = output.replace(r, "")
if filter_space:
output = output.replace(" ", "")
return output.replace("/", "") + "." + extension.lower()