Created
March 13, 2024 16:31
-
-
Save ayutaz/b5854648aed368c0ce1586b73b36ea66 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import glob | |
import os | |
from reazonspeech.nemo.asr import load_model, transcribe, audio_from_path | |
import csv | |
import json | |
import librosa | |
# 実行時にHugging Faceからモデルを取得します (2.3GB) | |
model = load_model(device='cuda') | |
# 対象のディレクトリパス | |
directory_path = 'root path' | |
# 指定されたディレクトリ以下のすべてのwavファイルのパスを取得 | |
wav_files = glob.glob(os.path.join(directory_path + "\\train", '**', '*.mp3'), recursive=True) | |
# CSVファイルとJSONファイルのパスを指定 | |
csv_file_path = f'{directory_path}\\transcription_results.csv' | |
json_file_path = f'{directory_path}\\transcription_results.json' | |
# 結果を格納するためのリスト | |
results = [] | |
# 全体のファイル数を取得 | |
total_files = len(wav_files) | |
# CSVファイルに保存 | |
with open(csv_file_path, mode='w', newline='', encoding='utf-8') as csv_file: | |
writer = csv.writer(csv_file) | |
writer.writerow(['ファイル名', 'テキスト内容', '音声の長さ']) | |
for index, file_path in enumerate(wav_files, start=1): | |
# ローカルの音声ファイルを読み込む | |
audio = audio_from_path(file_path) | |
# 音声認識を適用する | |
ret = transcribe(model, audio).text | |
# 音声の長さを取得 | |
duration = librosa.get_duration(filename=file_path) | |
# ファイルパスからファイル名のみを抽出 | |
file_name = os.path.basename(file_path) | |
print(f"{index}/{total_files}") | |
# 結果をリストに追加 | |
results.append({'ファイル名': file_name, 'テキスト内容': ret, '音声の長さ': duration}) | |
# CSVに書き込む | |
writer.writerow([file_name, ret, duration]) | |
# JSONファイルに保存 | |
with open(json_file_path, 'w', encoding='utf-8') as json_file: | |
json.dump(results, json_file, ensure_ascii=False, indent=4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment