|
import torch |
|
import librosa |
|
import json |
|
import numpy as np |
|
from datasets import load_dataset |
|
|
|
|
|
ds = load_dataset("reazon-research/reazonspeech", "all") |
|
|
|
|
|
if torch.cuda.is_available(): |
|
device = torch.device('cuda') |
|
else: |
|
print("エラー: GPUが利用可能ではありません。GPUを使用して実行してください。") |
|
exit(1) |
|
|
|
|
|
predictor = torch.hub.load("tarepan/SpeechMOS:v1.2.0", "utmos22_strong", trust_repo=True) |
|
|
|
|
|
predictor = predictor.to(device) |
|
|
|
|
|
def preprocess_audio(data): |
|
|
|
if data.dtype == np.int16: |
|
data = data.astype(np.float32) / np.iinfo(np.int16).max |
|
elif data.dtype == np.int32: |
|
data = data.astype(np.float32) / np.iinfo(np.int32).max |
|
|
|
|
|
if len(data.shape) == 2: |
|
data = data.mean(axis=1) |
|
|
|
return data |
|
|
|
def process_audio_data(data): |
|
|
|
audio_data = data['audio']['array'] |
|
sr = data['audio']['sampling_rate'] |
|
|
|
|
|
audio_data = preprocess_audio(audio_data) |
|
|
|
|
|
audio_data_tensor = torch.from_numpy(audio_data).unsqueeze(0).to(torch.float32).to(device) |
|
score = predictor(audio_data_tensor.to(torch.float32), sr) |
|
|
|
|
|
result = { |
|
"ファイル名": data['name'], |
|
"MOS値": float(score), |
|
"トランスクリプション": data['transcription'] |
|
} |
|
|
|
|
|
del audio_data, audio_data_tensor |
|
|
|
return result |
|
|
|
def process_and_save_results(ds): |
|
total_data = len(ds['train']) |
|
for i, data in enumerate(ds['train']): |
|
result = process_audio_data(data) |
|
print(f"処理中: {i+1}/{total_data} ({(i+1)/total_data*100:.2f}%)") |
|
yield result |
|
|
|
|
|
def save_results_to_json(ds): |
|
with open('audio_analysis_results_speechMOS.json', 'w', encoding='utf-8') as f: |
|
f.write('[\n') |
|
for i, result in enumerate(process_and_save_results(ds)): |
|
print("ファイル名:" + result["ファイル名"] + ", MOS値:" + str(result["MOS値"])) |
|
print("トランスクリプション: ", result["トランスクリプション"]) |
|
json.dump(result, f, ensure_ascii=False, indent=4) |
|
if i < len(ds['train']) - 1: |
|
f.write(',\n') |
|
f.write('\n]') |
|
|
|
print("JSONファイルが保存されました。") |
|
|
|
|
|
save_results_to_json(ds) |