| |
| |
|
|
| import os |
| import librosa |
| from collections import Counter |
| from tqdm import tqdm |
| import sys |
|
|
| def is_leaf_dir(path): |
| """判断是否为最原子的子文件夹(无子文件夹)""" |
| for item in os.listdir(path): |
| if os.path.isdir(os.path.join(path, item)): |
| return False |
| return True |
|
|
|
|
| def get_wav_length(path): |
| try: |
| y, sr = librosa.load(path, sr=None, mono=True) |
| return round(len(y) / sr) |
| except Exception as e: |
| print(f"读取失败: {path} 错误: {e}") |
| return None |
|
|
|
|
| def main(noise_root): |
| noise_root = os.path.abspath(noise_root) |
|
|
| print("扫描所有 leaf(最原子)子文件夹...\n") |
| leaf_dirs = [] |
|
|
| |
| for dataset in os.listdir(noise_root): |
| dataset_path = os.path.join(noise_root, dataset) |
| if not os.path.isdir(dataset_path): |
| continue |
|
|
| |
| for root, dirs, files in os.walk(dataset_path): |
| if is_leaf_dir(root): |
| leaf_dirs.append(root) |
|
|
| print("发现的 leaf 文件夹:") |
| for d in leaf_dirs: |
| print(" -", d) |
|
|
| print("\n开始统计...\n") |
|
|
| all_results = {} |
|
|
| for leaf in leaf_dirs: |
| counter = Counter() |
| wav_count = 0 |
|
|
| |
| for f in tqdm(os.listdir(leaf), desc=f"[{leaf}]"): |
| if not f.lower().endswith(".wav"): |
| continue |
|
|
| wav_count += 1 |
| path = os.path.join(leaf, f) |
| L = get_wav_length(path) |
| if L is not None: |
| counter[L] += 1 |
|
|
| all_results[leaf] = (wav_count, counter) |
|
|
| |
| print("\n============== 统计结果 ==============\n") |
|
|
| for leaf, (cnt, dist) in all_results.items(): |
| print(f"📁 {leaf}") |
| print(f" WAV 数量:{cnt}") |
| print(" 时长分布(秒):") |
| for L in sorted(dist): |
| print(f" {L:2d}s : {dist[L]}") |
| print() |
|
|
| print("统计完成!") |
|
|
|
|
| if __name__ == "__main__": |
| if len(sys.argv) < 2: |
| print("用法: python stats_leaf_folders.py <noise根目录>") |
| print("示例: python stats_leaf_folders.py noise") |
| sys.exit(1) |
|
|
| main(sys.argv[1]) |
|
|