asahi417's picture
nit refactoring
3524295
raw
history blame
2.01 kB
import json
import os
from os.path import join as p_join
from tqdm import tqdm
from typing import Dict
from glob import glob
import soundfile as sf
from datasets import Audio
# dataset config
direction = os.getenv("DIRECTION", "enA-jpn")
direction_speech = os.getenv("DIRECTION_SPEECH", "enA")
cache_dir_audio = p_join("download", "audio", direction)
cache_dir_feature = p_join("download", "feature", direction)
cache_dir_audio_fixed = p_join("download", "audio_fixed", direction, direction_speech)
os.makedirs(cache_dir_feature, exist_ok=True)
os.makedirs(cache_dir_audio, exist_ok=True)
os.makedirs(cache_dir_audio_fixed, exist_ok=True)
line_no_start = int(os.getenv("LINE_NO_START", 0))
line_no_end = int(os.getenv("LINE_NO_END", 100))
def loader(feature: str) -> Dict:
with open(feature) as f_reader:
return json.load(f_reader)
# feature dictionary
files = {
int(os.path.basename(i).replace(".json", "")): i for i in glob(p_join(cache_dir_feature, "*.json"))
}
# feature files
files_list = [k for k in files.keys() if line_no_start <= k <= line_no_end]
fixed_audio_list = [int(os.path.basename(i).replace(".mp3", "")) for i in glob(p_join(cache_dir_audio_fixed, "*"))]
# remove broken audio files
audio_loader = Audio()
index_list = [i for i in list(range(line_no_start, line_no_end)) if i in files_list and i not in fixed_audio_list]
print(f"filtering {len(index_list)} files....")
for i in tqdm(index_list):
features = loader(files[i])
audio_file = features[f"{direction_speech}.path"]
start, end = features[f"{direction_speech}.duration_start"], features[f"{direction_speech}.duration_end"]
if os.path.exists(audio_file):
try:
wav = audio_loader.decode_example({"path": audio_file, "bytes": None})
if start < end < len(wav["array"]):
sf.write(p_join(cache_dir_audio_fixed, f"{i}.mp3"), wav["array"][start:end], wav["sampling_rate"])
except Exception as e:
print(e)
os.remove(audio_file)