asahi417's picture
init
29d6c07
raw
history blame
2.23 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
from soundfile import LibsndfileError
from datasets import Audio
# dataset config
direction = os.getenv("DIRECTION", "enA-jaA")
sides = {i: n for n, i in enumerate(sorted(direction.split("-")), 1)}
sides_rev = {v: k for k, v in sides.items()}
cache_dir_audio = p_join("download", "audio", direction)
cache_dir_feature = p_join("download", "feature", direction)
os.makedirs(cache_dir_audio, exist_ok=True)
os.makedirs(cache_dir_feature, exist_ok=True)
line_no_start = int(os.getenv("LINE_NO_START", 0))
line_no_end = int(os.getenv("LINE_NO_END", 100000))
def loader(feature: str) -> Dict:
with open(feature) as f:
return json.load(f)
files = {
int(os.path.basename(i).replace(".json", "")): i for i in glob(p_join(cache_dir_feature, "*.json"))
}
audio_loader = Audio()
def delete_audio(target_audio_file):
if os.path.exists(target_audio_file):
os.remove(target_audio_file)
line_no = os.path.basename(target_audio_file).split(".")[0]
try:
feature_file = files[int(line_no)]
if os.path.exists(feature_file):
os.remove(feature_file)
except Exception as e:
print(e)
# remove broken audio files
n_broken_files = 0
for i in tqdm(list(range(line_no_start, line_no_end))):
if i not in files:
continue
i = loader(files[i])
for lang_side in [sides_rev[1], sides_rev[2]]:
if f"{lang_side}.path" not in i:
continue
audio_file = i[f"{lang_side}.path"]
start, end = i[f"{lang_side}.duration_start"], i[f"{lang_side}.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"]):
pass
else:
delete_audio(audio_file)
n_broken_files += 1
print(n_broken_files)
except Exception as e:
print(e)
delete_audio(audio_file)
n_broken_files += 1
print(n_broken_files)