音声認識とは、その名の通り、人間の話す言葉を自動的に認識することである。
音声認識は、ヒューマンコンピュータインタラクションの領域において、最も重要なタスクの1つです。
Alexaと対話したことがある人、Siriにタスクを完了するよう指示したことがある人は、すでに音声認識の威力を体験していることでしょう。
音声認識には、音声データの自動転写(ボイスメールなど)から、音声によるロボットとの対話まで、さまざまな用途があります。
このチュートリアルでは、オーディオファイルやマイクからの音声を認識することができる、非常にシンプルな音声認識アプリケーションを開発する方法について説明します。
では、さっそく始めましょう。
Pythonでは、いくつかの音声認識ライブラリが開発されています。
しかし、今回はその中でも最もシンプルなSpeechRecognitionライブラリを使用します。
SpeechRecognitionライブラリのインストール
以下のコマンドを実行し、ライブラリをインストールします。
$ pip install SpeechRecognition
音声ファイルからの音声認識
このセクションでは、音声ファイルからテキストに音声を変換する方法を説明します。
入力として使用する音声ファイルは、このリンクからダウンロードできます。
ファイルをローカルファイルシステムにダウンロードしてください。
最初のステップは、いつものように、必要なライブラリをインポートすることです。
今回は、先ほどダウンロードした speech_recognition
ライブラリをインポートすればよいでしょう。
import speech_recognition as speech_recog
音声をテキストに変換するために必要なクラスは、 speech_recognition
モジュールの Recognizer
クラスだけです。
音声をテキストに変換するために使用する API に応じて、Recognizer
クラスは以下のメソッドを持っている。
-
recognize_bing()
: Microsoft Bing Speech API を利用する。 -
recognize_google()
: Google Speech API を利用する。 -
recognize_google_cloud()
: Google Cloud Speech API を利用する。 -
recognize_houndify()
: SoundHound の Houndify API を利用する。 -
recognize_ibm()
: IBM Speech to Text API を利用する。 -
recognize_sphinx()
: PocketSphinxのAPIを利用する
上記のメソッドのうち、recognize_sphinx()
メソッドはオフラインで音声をテキストに変換するために使用することができます。
オーディオファイルから音声を認識するためには、 speech_recognition
モジュールの AudioFile
クラスのオブジェクトを作成する必要があります。
テキストに変換したいオーディオファイルのパスは AudioFile
クラスのコンストラクタに渡します。
以下のスクリプトを実行します。
sample_audio = speech_recog.AudioFile('E:/Datasets/my_audio.wav')
上記のコードの中で、文字化けしたいオーディオファイルのパスを更新します。
ここでは、recognize_google()
メソッドを使ってオーディオファイルを書き写すことにします。
しかし、recognize_google()
メソッドは speech_recognition
モジュールの AudioData
オブジェクトをパラメータとして必要とします。
オーディオファイルを AudioData
オブジェクトに変換するには、Recognizer
クラスの record()
メソッドを使用します。
以下のように、record()
メソッドに AudioFile
オブジェクトを渡す必要があります。
with sample_audio as audio_file:
audio_content = recog.record(audio_file)
ここで、変数 audio_content
の型を確認すると、 speech_recognition.AudioData
という型を持っていることが分かります。
type(audio_content)
出力します。
speech_recognition.AudioData
あとは、Audio_content
オブジェクトを Recognizer()
クラスオブジェクトの recognize_google()
メソッドに渡すだけで、音声ファイルがテキストに変換されます。
以下のスクリプトを実行してください。
recog.recognize_google(audio_content)
出力してください。
'Bristol O2 left shoulder take the winding path to reach the lake no closely the size of the gas tank degrees office 30 face before you go out the race was badly strained and hung them the stray cat gave birth to kittens the young girl gave no clear response the meal was called before the bells ring what weather is in living'
上記の出力は、オーディオファイルのテキストを示しています。
100%正しく書き写されているわけではありませんが、それなりの精度があることがわかります。
デュレーションとオフセット値の設定
スピーチ全体を書き写す代わりに、オーディオファイルの特定のセグメントを書き写すこともできます。
例えば、オーディオファイルの最初の10秒だけを書き起こしたい場合、 record()
メソッドの duration
パラメータに10を渡す必要があります。
次のスクリプトを見てください。
sample_audio = speech_recog.AudioFile('E:/Datasets/my_audio.wav')
with sample_audio as audio_file:
audio_content = recog.record(audio_file, duration=10)
recog.recognize_google(audio_content)
出力します。
'Bristol O2 left shoulder take the winding path to reach the lake no closely the size of the gas'
同じように、offset
パラメータを使えば、オーディオファイルのある部分を最初から飛ばすことができます。
例えば、オーディオの最初の4秒を書き写したくない場合は、offset
属性の値として 4 を渡します。
例として、次のスクリプトはオーディオファイルの最初の4秒をスキップし、その後10秒間のオーディオファイルを書き起こします。
sample_audio = speech_recog.AudioFile('E:/Datasets/my_audio.wav')
with sample_audio as audio_file:
audio_content = recog.record(audio_file, offset=4, duration=10)
recog.recognize_google(audio_content)
出力します。
'take the winding path to reach the lake no closely the size of the gas tank web degrees office dirty face'
ハンドリングノイズ
音声ファイルには、いくつかの理由によりノイズが含まれることがあります。
ノイズは実際に音声からテキストへの翻訳の品質に影響を与えることがあります。
ノイズを減らすために、Recognizer
クラスには adjust_for_ambient_noise()
メソッドがあり、 AudioData
オブジェクトを引数として受け取ります。
以下のスクリプトは、オーディオファイルからノイズを除去することによって、トランスクリプションの品質を向上させる方法を示しています。
sample_audio = speech_recog.AudioFile('E:/Datasets/my_audio.wav')
with sample_audio as audio_file:
recog.adjust_for_ambient_noise(audio_file)
audio_content = recog.record(audio_file)
recog.recognize_google(audio_content)
出力します。
'Bristol O2 left shoulder take the winding path to reach the lake no closely the size of the gas tank web degrees office 30 face before you go out the race was badly strained and hung them the stray cat gave birth to kittens the younger again no clear response the mail was called before the bells ring what weather is in living'
これは、オーディオファイルにすでにほとんどノイズがないためです。
生マイクロフォンからの音声認識
このセクションでは、システム上のマイクで受信したライブ音声をどのように書き写すかについて説明します。
マイクから受信した音声を処理する方法はいくつかあり、そのためのライブラリもいろいろと開発されています。
そのようなライブラリの1つがPyAudioです。
以下のスクリプトを実行して、PyAudio
ライブラリをインストールします。
$ pip install PyAudio
さて、文字起こしをする音声のソースはマイクです。
マイクから音声を取り込むには、まず、次のように Speach_Recogniton
モジュールの Microphone
クラスのオブジェクトを作成する必要があります。
mic = speech_recog.Microphone()
システム内のすべてのマイクのリストを見るには、 list_microphone_names()
メソッドを使用します。
speech_recog.Microphone.list_microphone_names()
出力します。
['Microsoft Sound Mapper - Input',
'Microphone (Realtek High Defini',
'Microsoft Sound Mapper - Output',
'Speakers (Realtek High Definiti',
'Microphone Array (Realtek HD Audio Mic input)',
'Speakers (Realtek HD Audio output)',
'Stereo Mix (Realtek HD Audio Stereo input)']
これは私のシステムで利用可能なマイクロフォンのリストです。
あなたのリストはおそらく違うものになることを心に留めておいてください。
次のステップは、マイクからの音声を取り込むことです。
これを行うには、 Recognizer()
クラスの listen()
メソッドを呼び出す必要があります。
record()メソッドと同様に、
listen()メソッドも
speech_recognition.AudioDataオブジェクトを返し、これを
recognize_google()` メソッドに渡します。
次のスクリプトは、マイクに向かって何かを言うように促し、ユーザーが言ったことをそのまま表示します。
with mic as audio_file:
print("Speak Please")
recog.adjust_for_ambient_noise(audio_file)
audio = recog.listen(audio_file)
print("Converting Speech to Text...")
print("You said: " + recog.recognize_google(audio))
上記のスクリプトを実行すると、次のようなメッセージが表示されます。
Please say something
この時点で、好きなことを言って、一時停止してください。
一時停止をすると、あなたが言ったことが文字化けします。
以下は、私が得た出力である。
Converting Speech to Text...
You said: hello this is normally from stack abuse abuse this is an article on speech recognition I hope you will like it and this is just a test speech and when I will stop speaking are you in today thank you for Reading
重要なことは、もし recognize_google()
メソッドが、あなたが話した単語をリポジトリ内のどの単語ともマッチングできない場合、例外が投げられるということです。
これをテストするには、意味不明な単語をいくつか言ってみてください。
以下のような例外が表示されるはずです。
Speak Please
Converting Speech to Text...
---------------------------------------------------------------------------
UnknownValueError Traceback (most recent call last)
<ipython-input-27-41218bc8a239 in <module
8 print("Converting Speech to Text...")
9
---> 10 print("You said: " + recog.recognize_google(audio))
11
12
~Anaconda3libsite-packagesspeech_recognition__init__.py in recognize_google(self, audio_data, key, language, show_all)
856 # return results
857 if show_all: return actual_result
--> 858 if not isinstance(actual_result, dict) or len(actual_result.get("alternative", [])) == 0: raise UnknownValueError()
859
860 if "confidence" in actual_result["alternative"]:
UnknownValueError:
よりよい方法は、以下のように recognize_google()
メソッドが呼ばれたときに try
ブロックを使用することです。
with mic as audio_file:
print("Speak Please")
recog.adjust_for_ambient_noise(audio_file)
audio = recog.listen(audio_file)
print("Converting Speech to Text...")
try:
print("You said: " + recog.recognize_google(audio))
except Exception as e:
print("Error: " + str(e))
結論
音声認識は、ヒューマンコンピュータインタラクションや自動音声転写の領域で様々な有用なアプリケーションを持っています。
この記事では、Pythonの speech_recognition
ライブラリを使った音声転写のプロセスを簡単に説明し、オーディオファイルやライブマイクを音源とした場合の音声からテキストへの変換方法について説明します。