File size: 2,379 Bytes
efa83a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

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 = []

    # 遍历 noise 根目录下所有文件夹
    for dataset in os.listdir(noise_root):  # MUSAN、DEMAND、ESC50 …
        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

        # 遍历该 leaf 下的所有 wav
        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])