Delete DESED/DESED_dataset/timing.py
Browse files- DESED/DESED_dataset/timing.py +0 -247
DESED/DESED_dataset/timing.py
DELETED
|
@@ -1,247 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import sys
|
| 3 |
-
import soundfile as sf
|
| 4 |
-
import numpy as np
|
| 5 |
-
from pathlib import Path
|
| 6 |
-
import argparse
|
| 7 |
-
from collections import defaultdict
|
| 8 |
-
import traceback
|
| 9 |
-
|
| 10 |
-
def get_audio_duration(audio_path):
|
| 11 |
-
"""获取音频文件的时长(秒)"""
|
| 12 |
-
try:
|
| 13 |
-
# 使用soundfile获取音频信息
|
| 14 |
-
info = sf.info(audio_path)
|
| 15 |
-
duration = info.duration
|
| 16 |
-
return duration, info.samplerate, info.channels
|
| 17 |
-
except Exception as e:
|
| 18 |
-
print(f"警告: 无法读取音频文件 {audio_path}: {e}")
|
| 19 |
-
return None, None, None
|
| 20 |
-
|
| 21 |
-
def analyze_audio_folder(folder_path, extensions=None):
|
| 22 |
-
"""分析文件夹中所有音频文件的时长"""
|
| 23 |
-
|
| 24 |
-
if extensions is None:
|
| 25 |
-
extensions = ['.wav', '.mp3', '.flac', '.ogg', '.m4a', '.aac', '.wma']
|
| 26 |
-
|
| 27 |
-
# 确保扩展名都是小写
|
| 28 |
-
extensions = [ext.lower() for ext in extensions]
|
| 29 |
-
|
| 30 |
-
folder_path = Path(folder_path)
|
| 31 |
-
|
| 32 |
-
if not folder_path.exists():
|
| 33 |
-
print(f"错误: 文件夹不存在: {folder_path}")
|
| 34 |
-
return None
|
| 35 |
-
|
| 36 |
-
print(f"正在分析文件夹: {folder_path}")
|
| 37 |
-
print(f"支持的音频格式: {', '.join(extensions)}")
|
| 38 |
-
print("-" * 50)
|
| 39 |
-
|
| 40 |
-
# 收集所有音频文件
|
| 41 |
-
audio_files = []
|
| 42 |
-
for ext in extensions:
|
| 43 |
-
# 递归查找所有音频文件
|
| 44 |
-
pattern = f"**/*{ext}"
|
| 45 |
-
files = list(folder_path.glob(pattern))
|
| 46 |
-
audio_files.extend(files)
|
| 47 |
-
|
| 48 |
-
if not audio_files:
|
| 49 |
-
print("未找到任何音频文件")
|
| 50 |
-
return None
|
| 51 |
-
|
| 52 |
-
print(f"找到 {len(audio_files)} 个音频文件")
|
| 53 |
-
|
| 54 |
-
# 分析每个音频文件
|
| 55 |
-
durations = []
|
| 56 |
-
sample_rates = []
|
| 57 |
-
channels_info = []
|
| 58 |
-
failed_files = []
|
| 59 |
-
|
| 60 |
-
format_stats = defaultdict(list)
|
| 61 |
-
|
| 62 |
-
for i, audio_file in enumerate(audio_files):
|
| 63 |
-
if (i + 1) % 100 == 0:
|
| 64 |
-
print(f"进度: {i+1}/{len(audio_files)} ({(i+1)/len(audio_files)*100:.1f}%)")
|
| 65 |
-
|
| 66 |
-
duration, sample_rate, channels = get_audio_duration(audio_file)
|
| 67 |
-
|
| 68 |
-
if duration is not None:
|
| 69 |
-
durations.append(duration)
|
| 70 |
-
sample_rates.append(sample_rate)
|
| 71 |
-
channels_info.append(channels)
|
| 72 |
-
|
| 73 |
-
# 按文件格式分类统计
|
| 74 |
-
file_ext = audio_file.suffix.lower()
|
| 75 |
-
format_stats[file_ext].append(duration)
|
| 76 |
-
else:
|
| 77 |
-
failed_files.append(audio_file)
|
| 78 |
-
|
| 79 |
-
if not durations:
|
| 80 |
-
print("没有成功读取任何音频文件")
|
| 81 |
-
return None
|
| 82 |
-
|
| 83 |
-
# 计算统计信息
|
| 84 |
-
durations = np.array(durations)
|
| 85 |
-
sample_rates = np.array(sample_rates)
|
| 86 |
-
|
| 87 |
-
total_duration = np.sum(durations)
|
| 88 |
-
avg_duration = np.mean(durations)
|
| 89 |
-
max_duration = np.max(durations)
|
| 90 |
-
min_duration = np.min(durations)
|
| 91 |
-
median_duration = np.median(durations)
|
| 92 |
-
std_duration = np.std(durations)
|
| 93 |
-
|
| 94 |
-
# 找出最长和最短的文件
|
| 95 |
-
max_idx = np.argmax(durations)
|
| 96 |
-
min_idx = np.argmin(durations)
|
| 97 |
-
|
| 98 |
-
max_file = audio_files[max_idx] if max_idx < len(audio_files) else "未知"
|
| 99 |
-
min_file = audio_files[min_idx] if min_idx < len(audio_files) else "未知"
|
| 100 |
-
|
| 101 |
-
# 输出统计结果
|
| 102 |
-
print("\n" + "=" * 60)
|
| 103 |
-
print("音频文件时长统计结果")
|
| 104 |
-
print("=" * 60)
|
| 105 |
-
|
| 106 |
-
print(f"总文件数: {len(audio_files)}")
|
| 107 |
-
print(f"成功读取: {len(durations)}")
|
| 108 |
-
print(f"读取失败: {len(failed_files)}")
|
| 109 |
-
|
| 110 |
-
print(f"\n时长统计:")
|
| 111 |
-
print(f" 总时长: {total_duration:.2f} 秒 ({total_duration/60:.2f} 分钟, {total_duration/3600:.2f} 小时)")
|
| 112 |
-
print(f" 平均时长: {avg_duration:.2f} 秒")
|
| 113 |
-
print(f" 最大时长: {max_duration:.2f} 秒")
|
| 114 |
-
print(f" 最小时长: {min_duration:.2f} 秒")
|
| 115 |
-
print(f" 中位数时长: {median_duration:.2f} 秒")
|
| 116 |
-
print(f" 标准差: {std_duration:.2f} 秒")
|
| 117 |
-
|
| 118 |
-
print(f"\n文件信息:")
|
| 119 |
-
print(f" 最长文件: {max_file.name} ({max_duration:.2f}秒)")
|
| 120 |
-
print(f" 最短文件: {min_file.name} ({min_duration:.2f}秒)")
|
| 121 |
-
|
| 122 |
-
# 采样率统计
|
| 123 |
-
unique_sample_rates = np.unique(sample_rates)
|
| 124 |
-
print(f"\n采样率统计:")
|
| 125 |
-
for sr in unique_sample_rates:
|
| 126 |
-
count = np.sum(sample_rates == sr)
|
| 127 |
-
print(f" {sr} Hz: {count} 个文件")
|
| 128 |
-
|
| 129 |
-
# 声道数统计
|
| 130 |
-
unique_channels = np.unique(channels_info)
|
| 131 |
-
print(f"\n声道数统计:")
|
| 132 |
-
for ch in unique_channels:
|
| 133 |
-
count = np.sum(np.array(channels_info) == ch)
|
| 134 |
-
print(f" {ch} 声道: {count} 个文件")
|
| 135 |
-
|
| 136 |
-
# 按文件格式统计
|
| 137 |
-
print(f"\n按文件格式统计:")
|
| 138 |
-
for ext, ext_durations in format_stats.items():
|
| 139 |
-
ext_durations = np.array(ext_durations)
|
| 140 |
-
print(f" {ext}: {len(ext_durations)} 个文件")
|
| 141 |
-
print(f" 平均时长: {np.mean(ext_durations):.2f} 秒")
|
| 142 |
-
print(f" 最大时长: {np.max(ext_durations):.2f} 秒")
|
| 143 |
-
print(f" 最小时长: {np.min(ext_durations):.2f} 秒")
|
| 144 |
-
|
| 145 |
-
# 时长分布统计
|
| 146 |
-
print(f"\n时长分布统计:")
|
| 147 |
-
ranges = [(0, 10), (10, 30), (30, 60), (60, 180), (180, 600), (600, float('inf'))]
|
| 148 |
-
range_names = ["0-10秒", "10-30秒", "30-60秒", "1-3分钟", "3-10分钟", "10分钟以上"]
|
| 149 |
-
|
| 150 |
-
for (start, end), name in zip(ranges, range_names):
|
| 151 |
-
if end == float('inf'):
|
| 152 |
-
count = np.sum(durations >= start)
|
| 153 |
-
else:
|
| 154 |
-
count = np.sum((durations >= start) & (durations < end))
|
| 155 |
-
percentage = count / len(durations) * 100
|
| 156 |
-
print(f" {name}: {count} 个文件 ({percentage:.1f}%)")
|
| 157 |
-
|
| 158 |
-
# 显示失败的文件
|
| 159 |
-
if failed_files:
|
| 160 |
-
print(f"\n读取失败的文件 ({len(failed_files)} 个):")
|
| 161 |
-
for failed_file in failed_files[:10]: # 只显示前10个
|
| 162 |
-
print(f" {failed_file}")
|
| 163 |
-
if len(failed_files) > 10:
|
| 164 |
-
print(f" ... 还有 {len(failed_files) - 10} 个文件")
|
| 165 |
-
|
| 166 |
-
print("\n" + "=" * 60)
|
| 167 |
-
|
| 168 |
-
return {
|
| 169 |
-
"total_files": len(audio_files),
|
| 170 |
-
"successful_files": len(durations),
|
| 171 |
-
"failed_files": len(failed_files),
|
| 172 |
-
"total_duration": total_duration,
|
| 173 |
-
"avg_duration": avg_duration,
|
| 174 |
-
"max_duration": max_duration,
|
| 175 |
-
"min_duration": min_duration,
|
| 176 |
-
"median_duration": median_duration,
|
| 177 |
-
"std_duration": std_duration,
|
| 178 |
-
"max_file": str(max_file),
|
| 179 |
-
"min_file": str(min_file),
|
| 180 |
-
"durations": durations.tolist(),
|
| 181 |
-
"sample_rates": sample_rates.tolist(),
|
| 182 |
-
"channels": channels_info,
|
| 183 |
-
"format_stats": {k: np.array(v).tolist() for k, v in format_stats.items()},
|
| 184 |
-
"failed_files": [str(f) for f in failed_files]
|
| 185 |
-
}
|
| 186 |
-
|
| 187 |
-
def main():
|
| 188 |
-
parser = argparse.ArgumentParser(description='分析文件夹中音频文件的时长统计')
|
| 189 |
-
parser.add_argument('folder', help='要分析的文件夹路径')
|
| 190 |
-
parser.add_argument('--extensions', nargs='*',
|
| 191 |
-
default=['.wav', '.mp3', '.flac', '.ogg', '.m4a', '.aac', '.wma'],
|
| 192 |
-
help='支持的音频文件扩展名')
|
| 193 |
-
parser.add_argument('--output', '-o', help='输出JSON结果文件路径')
|
| 194 |
-
|
| 195 |
-
args = parser.parse_args()
|
| 196 |
-
|
| 197 |
-
try:
|
| 198 |
-
# 分析音频文件夹
|
| 199 |
-
results = analyze_audio_folder(args.folder, args.extensions)
|
| 200 |
-
|
| 201 |
-
if results and args.output:
|
| 202 |
-
import json
|
| 203 |
-
with open(args.output, 'w', encoding='utf-8') as f:
|
| 204 |
-
json.dump(results, f, ensure_ascii=False, indent=2)
|
| 205 |
-
print(f"\n详细结果已保存到: {args.output}")
|
| 206 |
-
|
| 207 |
-
except Exception as e:
|
| 208 |
-
print(f"程序执行出错: {e}")
|
| 209 |
-
traceback.print_exc()
|
| 210 |
-
sys.exit(1)
|
| 211 |
-
|
| 212 |
-
if __name__ == "__main__":
|
| 213 |
-
# 如果没有命令行参数,提供交互式使用
|
| 214 |
-
if len(sys.argv) == 1:
|
| 215 |
-
print("音频文件时长分析工具")
|
| 216 |
-
print("用法1: python timing.py <文件夹路径>")
|
| 217 |
-
print("用法2: python timing.py <文件夹路径> --output results.json")
|
| 218 |
-
print("用法3: python timing.py <文件夹路径> --extensions .wav .mp3")
|
| 219 |
-
print("\n交互式使用:")
|
| 220 |
-
|
| 221 |
-
folder_path = input("请输入要分析的文件夹路径: ").strip()
|
| 222 |
-
if not folder_path:
|
| 223 |
-
print("错误: 请提供有效的文件夹路径")
|
| 224 |
-
sys.exit(1)
|
| 225 |
-
|
| 226 |
-
# 使用默认设置分析
|
| 227 |
-
try:
|
| 228 |
-
results = analyze_audio_folder(folder_path)
|
| 229 |
-
|
| 230 |
-
# 询问是否保存结果
|
| 231 |
-
save_result = input("\n是否保存详细结果到JSON文件? (y/n): ").strip().lower()
|
| 232 |
-
if save_result in ['y', 'yes']:
|
| 233 |
-
output_file = input("请输入输出文件路径 (默认: audio_analysis_results.json): ").strip()
|
| 234 |
-
if not output_file:
|
| 235 |
-
output_file = "audio_analysis_results.json"
|
| 236 |
-
|
| 237 |
-
import json
|
| 238 |
-
with open(output_file, 'w', encoding='utf-8') as f:
|
| 239 |
-
json.dump(results, f, ensure_ascii=False, indent=2)
|
| 240 |
-
print(f"详细结果已保存到: {output_file}")
|
| 241 |
-
|
| 242 |
-
except Exception as e:
|
| 243 |
-
print(f"程序执行出错: {e}")
|
| 244 |
-
traceback.print_exc()
|
| 245 |
-
sys.exit(1)
|
| 246 |
-
else:
|
| 247 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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