#音声toTXT変換
import speech_recognition as sr
import soundfile as sf
from io import BytesIO
import os
r = sr.Recognizer()
def analyze_wav(wavfile):
try:
adata, samplerate = sf.read(BytesIO(wavfile.read()))
newpath = "new_file.wav"
path_tmp = os.path.join(os.path.dirname(os.path.abspath(__file__)), "tmp")
if not os.path.exists(path_tmp):
os.mkdir(path_tmp)
savepath = os.path.join(path_tmp, newpath)
sf.write(savepath, adata, samplerate)
with sr.AudioFile(savepath) as src:
audio = r.record(src)
txt = r.recognize_google(audio, language='ja-JP')
return txt
except:
import traceback
traceback.print_exc()
#サーバーで利用する場合(Flask)
from flask import Flask, request, abort
import speech_recognition as sr
import soundfile as sf
from io import BytesIO
import os
r = sr.Recognizer()
@app.route("/webapp", methods=['POST'])
def webapp():
wavdata = request.files["file"].stream
txt = analyze_wav(wavdata)
return txt
def analyze_wav(wavfile):
try:
adata, samplerate = sf.read(BytesIO(wavfile.read()))
newpath = "new_file.wav"
path_tmp = os.path.join(os.path.dirname(os.path.abspath(__file__)), "tmp")
if not os.path.exists(path_tmp):
os.mkdir(path_tmp)
savepath = os.path.join(path_tmp, newpath)
sf.write(savepath, adata, samplerate)
with sr.AudioFile(savepath) as src:
audio = r.record(src)
txt = r.recognize_google(audio, language='ja-JP')
return txt
except:
import traceback
traceback.print_exc()