Datasets:
File size: 3,982 Bytes
7083170 | 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 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 | import pandas as pd
import os
import torch
import torchaudio
import soundfile as sf
from tqdm import tqdm
target_sample_rate = 16000
df = pd.read_parquet('data.parquet')
# Rename columns
df = df.rename(columns={
'query_audio': 'query_audio_path',
'doc_audio': 'document_audio_path',
'query_duration': 'query_audio_duration',
'doc_duration': 'document_audio_duration',
})
# Get base directory (where convert.py is located)
base_dir = os.path.dirname(os.path.abspath(__file__)) if '__file__' in globals() else os.getcwd()
def check_and_resample_audio(audio_path, base_dir):
"""
检查音频文件的采样率,如果不是16kHz则重采样
Args:
audio_path: 音频文件的相对路径(在parquet中存储的路径)
base_dir: 基础目录路径
Returns:
(actual_sample_rate, needs_resample): 实际采样率和是否需要重采样
"""
if pd.isna(audio_path) or not audio_path or not audio_path.strip():
return None, False
# 构建完整路径
full_path = os.path.join(base_dir, audio_path)
if not os.path.exists(full_path):
print(f"警告: 音频文件不存在: {full_path}")
return None, False
try:
# 读取音频信息
info = sf.info(full_path)
actual_sample_rate = info.samplerate
# 检查是否需要重采样
if actual_sample_rate != target_sample_rate:
# 需要重采样
print(f"重采样: {audio_path} ({actual_sample_rate}Hz -> {target_sample_rate}Hz)")
# 加载音频
waveform, sample_rate = torchaudio.load(full_path)
# 转换为单声道(如果是立体声)
if waveform.shape[0] > 1:
waveform = torch.mean(waveform, dim=0, keepdim=True)
# 重采样
resampler = torchaudio.transforms.Resample(sample_rate, target_sample_rate)
waveform_resampled = resampler(waveform)
# 转换为numpy并确保在[-1, 1]范围内
waveform_np = waveform_resampled.squeeze().numpy()
waveform_np = waveform_np.clip(-1.0, 1.0)
# 保存为16kHz, 16-bit WAV
sf.write(full_path, waveform_np, target_sample_rate, subtype='PCM_16')
return target_sample_rate, True
else:
# 采样率正确,不需要重采样
return actual_sample_rate, False
except Exception as e:
print(f"错误: 处理音频文件 {full_path} 时出错: {e}")
return None, False
# 处理query音频文件
print("检查并重采样query音频文件...")
query_sample_rates = []
query_resampled_count = 0
for idx, audio_path in enumerate(tqdm(df['query_audio_path'], desc="处理query音频")):
sample_rate, was_resampled = check_and_resample_audio(audio_path, base_dir)
query_sample_rates.append(sample_rate if sample_rate else target_sample_rate)
if was_resampled:
query_resampled_count += 1
df['query_audio_sample_rate'] = query_sample_rates
# 处理document音频文件
print("检查并重采样document音频文件...")
doc_sample_rates = []
doc_resampled_count = 0
for idx, audio_path in enumerate(tqdm(df['document_audio_path'], desc="处理document音频")):
sample_rate, was_resampled = check_and_resample_audio(audio_path, base_dir)
doc_sample_rates.append(sample_rate if sample_rate else target_sample_rate)
if was_resampled:
doc_resampled_count += 1
df['document_audio_sample_rate'] = doc_sample_rates
# 保存更新后的parquet
df.to_parquet('data.parquet', index=False)
print(f'\n完成!')
print(f'Query音频: 重采样了 {query_resampled_count}/{len(df)} 个文件')
print(f'Document音频: 重采样了 {doc_resampled_count}/{len(df)} 个文件')
print(f'新列: {df.columns.tolist()}')
print(f'形状: {df.shape}')
print(df.head(2))
|