def speech(request):
import os
from google.cloud import storage
from google.cloud import speech
from google.cloud import firestore
import re
# for local
key_path = './app1/key/xxx.json'
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = key_path
CLOUD_STORAGE_BUCKET = 'xxx'
CLOUD_STORAGE_BUCKET2 = 'xxx'
# for deploy
#CLOUD_STORAGE_BUCKET = os.environ['CLOUD_STORAGE_BUCKET']
#CLOUD_STORAGE_BUCKET2 = os.environ['CLOUD_STORAGE_BUCKET2']
path = 'gs://' + CLOUD_STORAGE_BUCKET + '/'
if request.method == 'POST':
form = SpeechForm(request.POST, request.FILES)
if form.is_valid():
blob_name = form.cleaned_data['name']
sp = request.FILES['speech']
#speech = form.cleaned_data['speech']
# Cloud Storage
client_storage = storage.Client()
bucket = client_storage.get_bucket(CLOUD_STORAGE_BUCKET)
blob = bucket.blob(blob_name)
blob.upload_from_string(
sp.read(),
)
# Cloud Speech
client_speech = speech.SpeechClient()
gcs_uri = 'gs://'+CLOUD_STORAGE_BUCKET+'/'+blob_name
audio = speech.types.RecognitionAudio(uri=gcs_uri)
config = speech.types.RecognitionConfig(
#encoding=speech.enums.RecognitionConfig.AudioEncoding.FLAC,
encoding=speech.enums.RecognitionConfig.AudioEncoding.LINEAR16,
sample_rate_hertz=16000,
language_code='ja-JP')
operation = client_speech.long_running_recognize(config, audio)
response = operation.result()
text = response.results[0].alternatives[0].transcript
# Cloud Storage
client_storage = storage.Client()
bucket = client_storage.get_bucket(CLOUD_STORAGE_BUCKET2)
blob = bucket.blob(blob_name)
blob.upload_from_string(
text,
)
sales = 0
s = re.search('売上高', text)
if s is not None:
text2 = text[s.end():s.end()+20]
s2 = re.search('[0-9]+\S円', text2)
sales = s2.group()
o_income = 0
s = re.search('営業利益', text)
if s is not None:
text2 = text[s.end():s.end()+20]
s2 = re.search('[0-9]+\S円', text2)
o_income = s2.group()
n_income = 0
s = re.search('純利益', text)
if s is not None:
text2 = text[s.end():s.end()+20]
s2 = re.search('[0-9]+\S円', text2)
n_income = s2.group()
# Cloud Firestore
firestore_client = firestore.Client()
doc_ref = firestore_client.collection('texts').document(blob_name)
sales = sales
o_income = o_income
n_income = n_income
doc_ref.set({
'sales': sales,
'o_income': o_income,
'n_income': n_income,
})
d = {
'text': text,
'sales': sales,
'o_income': o_income,
'n_income': n_income,
}
return render(request, 'app1/text.html', d)
else:
form = SpeechForm()
d = {
'form': form,
}
return render(request, 'app1/speech.html', d)