Skip to content

Instantly share code, notes, and snippets.

@ayutaz
Created March 13, 2024 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ayutaz/b5854648aed368c0ce1586b73b36ea66 to your computer and use it in GitHub Desktop.
Save ayutaz/b5854648aed368c0ce1586b73b36ea66 to your computer and use it in GitHub Desktop.
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