Содержание
- 0.1 Выбор API для распознавания речи
- 0.2 Подготовка к использованию Google Cloud Speech API
- 0.3 Пример Asterisk dialplan
- 0.4 Заключение
- 1 Speech-to-text conversion powered by machine learning.
- 2 Powerful speech recognition
- 3 Powered by machine learning
- 4 Recognizes 120 languages and variants
- 5 Automatically identifies spoken language
- 6 Returns text transcription in real time for short-form or long-form audio
- 7 Automatically transcribes proper nouns and context-specific formatting
- 8 Offers selection of pre-built models, tailored for your use case
Выбор API для распознавания речи
Я рассматривал только вариант api, коробочные решения были не нужны, поскольку требовали ресурсы, данные для распознания не критичны для бизнеса, да и использование их существенно сложнее и требует больше человеко-часов. Первым был Yandex SpeechKit Cloud. Мне он сразу понравился простотой использования:
curl -X POST -H "Content-Type: audio/x-wav" --data-binary "@speech.wav" "https://asr.yandex.net/asr_xml?uuid=<идентификатор пользователя>&key=&topic=queries"
Ценовая политика 400 рублей за 1000 запросов. Первый месяц бесплатно. Но после этого пошли только разочарования: — На передачу большого предложения, приходил ответ из 2-3 слов — Распознавались эти слова в странной последовательности — Попытки изменения топика положительных результатов не принесли Возможно это было связано со средним качеством записи, мы все тестировали через голосовые шлюзы и древние телефоны panasonic. Пока планирую его в дальнейшем использовать для построения IVR. Следующим стал сервис от Google. Интернет пестрит статьями, в которых предлагается использовать API для разработчиков Chromium. Сейчас ключей для этого API уже так просто получить нельзя. Поэтому мы будем использовать коммерческую платформу. Ценовая политика — 0-60 минут в месяц бесплатно. Далее 0,006 $ за 15 секунд речи. Каждый запрос округляется к цифре кратной 15. Первые два месяца бесплатно, для создания проекта нужна кредитная карта. Варианты использования API в базовой документации разнообразны. Мы будем использовать скрипт на Python:
"""Google Cloud Speech API sample application using the REST API for batch processing.""" import argparse import base64 import json from googleapiclient import discovery import httplib2 from oauth2client.client import GoogleCredentials DISCOVERY_URL = ('https://{api}.googleapis.com/$discovery/rest?' 'version={apiVersion}') def get_speech_service(): credentials = GoogleCredentials.get_application_default().create_scoped( ['https://www.googleapis.com/auth/cloud-platform']) http = httplib2.Http() credentials.authorize(http) return discovery.build( 'speech', 'v1beta1', http=http, discoveryServiceUrl=DISCOVERY_URL) def main(speech_file): """Transcribe the given audio file. Args: speech_file: the name of the audio file. """ with open(speech_file, 'rb') as speech: speech_content = base64.b64encode(speech.read()) service = get_speech_service() service_request = service.speech().syncrecognize( body={ 'config': { 'encoding': 'LINEAR16', # raw 16-bit signed LE samples 'sampleRate': 16000, # 16 khz 'languageCode': 'en-US', # a BCP-47 language tag }, 'audio': { 'content': speech_content.decode('UTF-8') } }) response = service_request.execute() print(json.dumps(response)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( 'speech_file', help='Full path of audio file to be recognized') args = parser.parse_args() main(args.speech_file)
Подготовка к использованию Google Cloud Speech API
Нам необходимо будет зарегистрировать проект и создать ключ сервисного аккаунта для авторизации. Вот ссылка для получения триала, необходим гугл-аккаунт. После регистрации необходимо активировать API и создать ключ для авторизации. После необходимо скопировать ключ на сервер. Перейдем к настройке самого сервера, нам необходимы будут: — python — python-pip — python google api client
sudo apt-get install -y python python-pip pip install --upgrade google-api-python-client
Теперь нам необходимо экспортировать две переменных окружения, для успешной работы с апи. Первая это путь к сервисному ключу, вторая название вашего проекта.
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service_account_file.json export GCLOUD_PROJECT=your-project-id
Скачаем тестовый аудио файл и попытаемся запустить скрипт:
wget https://cloud.google.com/speech/docs/samples/audio.raw python voice.py audio.raw {"results": [{"alternatives": [{"confidence": 0.98267895, "transcript": "how old is the Brooklyn Bridge"}]}]}
Отлично! Первый тест успешен. Теперь изменим в скрипте язык распознавания текста и попробуем распознать его:
nano voice.py service_request = service.speech().syncrecognize( body={ 'config': { 'encoding': 'LINEAR16', # raw 16-bit signed LE samples 'sampleRate': 16000, # 16 khz 'languageCode': 'ru-RU', # a BCP-47 language tag
Нам необходим .raw аудио файл. Используем для этого sox
apt-get install -y sox sox test.wav -r 16000 -b 16 -c 1 test.raw python voice.py test.raw {"results": [{"alternatives": [{"confidence": 0.96161985, "transcript": "u0417u0434u0440u0430u0432u0441u0442u0432u0443u0439u0442u0435 u0412u0430u0441 u043fu0440u0438u0432u0435u0442u0441u0442u0432u0443u0435u0442 u043au043eu043cu043fu0430u043du0438u044f"}]}]}
Гугл возвращает нам ответ в юникоде. Но мы хотим видеть нормальные буквы. Поменяем немного наш voice.py: Вместо
print(json.dumps(response))
Мы будем использовать
s = simplejson.dumps({'var': response}, ensure_ascii=False) print s
Добавим import simplejson. Итоговый скрипт под катом:
"""Google Cloud Speech API sample application using the REST API for batch processing.""" import argparse import base64 import json import simplejson from googleapiclient import discovery import httplib2 from oauth2client.client import GoogleCredentials DISCOVERY_URL = ('https://{api}.googleapis.com/$discovery/rest?' 'version={apiVersion}') def get_speech_service(): credentials = GoogleCredentials.get_application_default().create_scoped( ['https://www.googleapis.com/auth/cloud-platform']) http = httplib2.Http() credentials.authorize(http) return discovery.build( 'speech', 'v1beta1', http=http, discoveryServiceUrl=DISCOVERY_URL) def main(speech_file): """Transcribe the given audio file. Args: speech_file: the name of the audio file. """ with open(speech_file, 'rb') as speech: speech_content = base64.b64encode(speech.read()) service = get_speech_service() service_request = service.speech().syncrecognize( body={ 'config': { 'encoding': 'LINEAR16', # raw 16-bit signed LE samples 'sampleRate': 16000, # 16 khz 'languageCode': 'en-US', # a BCP-47 language tag }, 'audio': { 'content': speech_content.decode('UTF-8') } }) response = service_request.execute() s = simplejson.dumps({'var': response}, ensure_ascii=False) print s if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( 'speech_file', help='Full path of audio file to be recognized') args = parser.parse_args() main(args.speech_file)
Но перед его запуском нужно будет экспортировать ещё одну переменную окружения export PYTHONIOENCODING=UTF-8. Без неё у меня возникли проблемы с stdout при вызове в скриптах.
export PYTHONIOENCODING=UTF-8 python voice.py test.raw {"var": {"results": [{"alternatives": [{"confidence": 0.96161985, "transcript": "Здравствуйте Вас приветствует компания"}]}]}}
Отлично. Теперь мы можем вызывать этот скрипт в диалплане.
Пример Asterisk dialplan
Для вызова скрипта я буду использовать простенький диалплан:
exten => 1234,1,Answer exten => 1234,n,wait(1) exten => 1234,n,Playback(howtomaketicket) exten => 1234,n,Playback(beep) exten => 1234,n,Set(FILE=${CALLERID(num)}--${EXTEN}--${STRFTIME(${EPOCH},,%d-%m-%Y--%H-%M-%S)}.wav) exten => 1234,n,MixMonitor(${FILE},,/opt/test/send.sh support@test.net "${CDR(src)}" "${CALLERID(name)}" "${FILE}") exten => 1234,n,wait(28) exten => 1234,n,Playback(beep) exten => 1234,n,Playback(Thankyou!) exten => 1234,n,Hangup()
Я использую для записи mixmonitor и после окончания запускаю скрипт. Можно использовать record и это, пожалуй, будет лучше. Пример send.sh для отправки — он предполагает, что у вас уже настроен mutt:
#!/bin/bash #скрипт для отправки уведомлений # экспортируем необходимые переменные окружения # файл лицензии гугла export GOOGLE_APPLICATION_CREDENTIALS=/opt/test/project.json # название проекта export GCLOUD_PROJECT=project-id # кодировка для питона export PYTHONIOENCODING=UTF-8 #список переменных на входе EMAIL=$1 CALLERIDNUM=$2 CALLERIDNAME=$3 FILE=$4 # перекодируем звуковой файл в raw для того, чтобы отдать его гугл апи sox /var/spool/asterisk/monitor/$FILE -r 16000 -b 16 -c 1 /var/spool/asterisk/monitor/$FILE.raw # присваиваем переменной значение выполненного скрипта по конвертации звука в текст и обрезаем не нужное TEXT=`python /opt/test/voice.py /var/spool/asterisk/monitor/$FILE.raw | sed -e 's/.*transcript"://' -e 's/}]}]}}//'` # отправляем письмо, включаем в письмо распознанный текст echo "новое уведомление от номера: $CALLERIDNUM $CALLERIDNAME $TEXT " | mutt -s "Это заголовок письма" -e 'set from=test@test.net realname="я присылаю оповещения"' -a "/var/spool/asterisk/monitor/$FILE" -- $EMAIL
Заключение
Таким образом мы решили поставленную задачу. Надеюсь кому-то пригодится мой опыт. Буду рад комментариям (пожалуй только ради этого и стоит читать Хабр!). В будущем планирую реализовать на основе этого IVR с элементами голосового управления.

Speech-to-text conversion powered by machine learning.
Powerful speech recognition
Google Cloud Speech-to-Text enables developers to convert audio to text by applying powerful neural network models in an easy-to-use API. The API recognizes 120 languages and variants to support your global user base. You can enable voice command-and-control, transcribe audio from call centers, and more. It can process real-time streaming or prerecorded audio, using Google’s machine learning technology.

Convert your speech to text right now
Powered by machine learning
Apply the most advanced deep-learning neural network algorithms to audio for speech recognition with unparalleled accuracy. Accuracy improves over time as Google improves the internal speech recognition technology used by Google products.

Recognizes 120 languages and variants
Cloud Speech-to-Text can support your global user base, recognizing 120 languages and variants. You can also filter inappropriate content in text results for all languages.

Automatically identifies spoken language
Using Cloud Speech-to-Text you can identify what language is spoken in the utterance (up to four languages). This can be used for voice search (such as, “What is the temperature in Paris?”) and command use cases (such as, “Turn the volume up.”)

Returns text transcription in real time for short-form or long-form audio
Cloud Speech-to-Text can stream text results, immediately returning text as it’s recognized from streaming audio or as the user is speaking. Alternatively, Cloud Speech-to-Text can return recognized text from audio stored in a file. It’s capable of analyzing short-form and long-form audio.

Automatically transcribes proper nouns and context-specific formatting
Cloud Speech-to-Text is tailored to work well with real-life speech and can accurately transcribe proper nouns (e.g., names, places) and appropriately format language (e.g., dates, phone numbers). Google supports more than 10x proper nouns compared to the number of words in the entire Oxford English Dictionary.

Offers selection of pre-built models, tailored for your use case
Cloud Speech-to-Text comes with multiple pre-built speech recognition models so you can optimize for your use case (such as voice commands). Example: Our pre-built video transcription model is ideal for indexing or subtitling video and/or multispeaker content and uses machine learning technology that is similar to YouTube captioning.

Model | Description |
---|---|
command_and_search | Best for short queries such as voice commands or voice search. |
phone_call | Best for audio that originated from a phone call (typically recorded at an 8khz sampling rate). |
video | Best for audio that originated from video or includes multiple speakers. Ideally the audio is recorded at a 16khz or greater sampling rate. This is a premium model that costs more than the standard rate. |
default | Best for audio that is not one of the specific audio models. For example, long-form audio. Ideally the audio is high-fidelity, recorded at a 16khz or greater sampling rate. |

- Automatic speech recognition
- Automatic speech recognition (ASR) powered by deep learning neural networking to power your applications like voice search or speech transcription.
- Global vocabulary
- Recognizes 120 languages and variants with an extensive vocabulary.
- Customized speech recognition
- Manually customize speech recognition for your business by specifying up to 5,000 words or phrases that are likely to be spoken (such as product names). Also automatically convert spoken numbers into addresses, years, or currencies, or do other conversions, depending on context.
- Real-time streaming or prerecorded audio support
- Audio input can be streamed from an application’s microphone or sent from a prerecorded audio file (inline or through Google Cloud Storage). Multiple audio encodings are supported, including FLAC, AMR, PCMU, and Linear-16.
- Auto-Detect Language (beta)
- When you need to support multilingual scenarios, you can now specify two to four language codes and Cloud Speech-to-Text will identify the correct language spoken and provide the transcript.
- Noise robustness
- Handles noisy audio from many environments without requiring additional noise cancellation.
- Inappropriate content filtering
- Filter inappropriate content in text results for some languages.
- Automatic Punctuation (beta)
- Accurately punctuates transcriptions (e.g., commas, question marks, and periods) with machine learning.
- Model selection
- Choose from a selection of four pre-built models: default, voice commands and search, phone calls, and video transcription.
- Speaker Diarization (beta)
- Know who said what you can now get automatic predictions about which of the speakers in a conversation spoke each utterance.
- Multichannel recognition
- In multiparticipant recordings where each participant is recorded in a separate channel (e.g., phone call with two channels or video conference with four channels), Cloud Speech-to-Text will recognize each channel separately and then annotate the transcripts so that they follow the same order as in real life.
Pricing
Cloud Speech-to-Text is priced per 15 seconds of audio processed after a 60-minute free tier. For details, please see our pricing guide.
Feature | Standard models (all models except enhanced phone and video) | Premium models* (enhanced phone, video) | ||
---|---|---|---|---|
0-60 Minutes | Over 60 Mins up to 1 Million Mins | 0-60 Minutes | Over 60 Mins up to 1 Million Mins | |
Speech Recognition (without Data Logging — default) | Free | $0.006 / 15 seconds ** | Free | $0.009 / 15 seconds ** |
Speech Recognition (with Data Logging opt-in) | Free | $0.004 / 15 seconds ** | Free | $0.006 / 15 seconds ** |
This pricing is for applications on personal systems (e.g., phones, tablets, laptops, desktops). Please contact us for approval and pricing to use the Cloud Speech-to-Text API on embedded devices (e.g., cars, TVs, appliances, or speakers).
* Currently available for US English only
** Each request is rounded up to the nearest increment of 15 seconds. For example, if you make three separate requests (Standard model), each containing 7 seconds of audio, you are billed $0.018 USD for 45 seconds (3 × 15 seconds) of audio. Fractions of seconds are included when rounding up to the nearest increment of 15 seconds. That is, 15.14 seconds are rounded up and billed as 30 seconds.

A product or feature listed on this page is in beta. For more information on our product launch stages, see here.
Cloud AI products comply with the SLA policies listed here. They may offer different latency or availability guarantees from other Google Cloud services.
- https://m.habr.com/post/310622/
- https://m.habr.com/ru/post/392205/
- https://cloud.google.com/speech-to-text/