nx_noise / examples /total_duration.py
HoneyTian's picture
update
1f06ccd
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
python3 total_duration.py --noise_dir /data/tianxing/HuggingDatasets/nx_noise/data/noise
python3 total_duration.py --noise_dir /data/tianxing/HuggingDatasets/nx_noise/data/speech
"""
import argparse
from collections import defaultdict
import os
from pathlib import Path
import sys
pwd = os.path.abspath(os.path.dirname(__file__))
sys.path.append(os.path.join(pwd, "../"))
import librosa
from tqdm import tqdm
from project_settings import project_path
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--noise_dir",
default=(project_path / "data/noise").as_posix(),
type=str
)
args = parser.parse_args()
return args
def main():
args = get_args()
counter = defaultdict(int)
duration_counter = defaultdict(float)
two_second_duration_counter = defaultdict(float)
three_second_duration_counter = defaultdict(float)
noise_dir = Path(args.noise_dir)
for filename in tqdm(list(noise_dir.glob("**/*.wav"))):
if filename.parts[-4] in ("noise", "speech"):
language = filename.parts[-3]
elif filename.parts[-3] in ("noise", "speech"):
language = filename.parts[-2]
else:
# raise AssertionError
continue
y, sr = librosa.load(filename, sr=None)
duration = librosa.get_duration(y=y, sr=sr)
two_second_duration = duration // 2 * 2
three_second_duration = duration // 3 * 3
counter[language] += 1
duration_counter[language] += round(duration, 4)
two_second_duration_counter[language] += round(two_second_duration, 4)
three_second_duration_counter[language] += round(three_second_duration, 4)
total_count = sum(counter.values())
total_duration = sum(duration_counter.values())
row = "\nduration; \n\n"
row += "| language | count | duration (m) | duration (h) |\n| :---: | :---: | :---: | :---: |\n"
for k, v in duration_counter.items():
row += f"| {k} | {counter[k]} | {round(v / 60, 2)} | {round(v / 3600, 2)} |\n"
row += f"| TOTAL | {total_count} | {round(total_duration, 2)} | {round(total_duration / 3600, 2)} |\n"
print(row)
total_duration = sum(two_second_duration_counter.values())
row = "\ntwo second duration; \n\n"
row += "| language | count | duration (m) | duration (h) |\n| :---: | :---: | :---: | :---: |\n"
for k, v in two_second_duration_counter.items():
row += f"| {k} | {counter[k]} | {round(v / 60, 2)} | {round(v / 3600, 2)} |\n"
row += f"| TOTAL | {total_count} | {round(total_duration, 2)} | {round(total_duration / 3600, 2)} |\n"
print(row)
total_duration = sum(three_second_duration_counter.values())
row = "\nthree second duration; \n\n"
row += "| language | count | duration (m) | duration (h) |\n| :---: | :---: | :---: | :---: |\n"
for k, v in three_second_duration_counter.items():
row += f"| {k} | {counter[k]} | {round(v / 60, 2)} | {round(v / 3600, 2)} |\n"
row += f"| TOTAL | {total_count} | {round(total_duration, 2)} | {round(total_duration / 3600, 2)} |\n"
print(row)
return
if __name__ == '__main__':
main()