__init__.py 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125
  1. #!/usr/bin/env python3
  2. """Library for performing speech recognition, with support for several engines and APIs, online and offline."""
  3. import io
  4. import os
  5. import subprocess
  6. import wave
  7. import aifc
  8. import math
  9. import audioop
  10. import collections
  11. import json
  12. import base64
  13. import threading
  14. import platform
  15. import stat
  16. import hashlib
  17. import hmac
  18. import time
  19. import uuid
  20. import tempfile
  21. import shutil
  22. import logging
  23. __author__ = "Anthony Zhang (Uberi)"
  24. __version__ = "3.5.0"
  25. __license__ = "BSD"
  26. try: # attempt to use the Python 2 modules
  27. from urllib import urlencode
  28. from urllib2 import Request, urlopen, URLError, HTTPError
  29. except ImportError: # use the Python 3 modules
  30. from urllib.parse import urlencode
  31. from urllib.request import Request, urlopen
  32. from urllib.error import URLError, HTTPError
  33. CACHED_GOOGLE_CLOUD_SPEECH_SERVICES = None
  34. class WaitTimeoutError(Exception): pass
  35. class RequestError(Exception): pass
  36. class UnknownValueError(Exception): pass
  37. class AudioSource(object):
  38. def __init__(self):
  39. raise NotImplementedError("this is an abstract class")
  40. def __enter__(self):
  41. raise NotImplementedError("this is an abstract class")
  42. def __exit__(self, exc_type, exc_value, traceback):
  43. raise NotImplementedError("this is an abstract class")
  44. class Microphone(AudioSource):
  45. """
  46. Creates a new ``Microphone`` instance, which represents a physical microphone on the computer. Subclass of ``AudioSource``.
  47. This will throw an ``AttributeError`` if you don't have PyAudio 0.2.9 or later installed.
  48. If ``device_index`` is unspecified or ``None``, the default microphone is used as the audio source. Otherwise, ``device_index`` should be the index of the device to use for audio input.
  49. A device index is an integer between 0 and ``pyaudio.get_device_count() - 1`` (assume we have used ``import pyaudio`` beforehand) inclusive. It represents an audio device such as a microphone or speaker. See the `PyAudio documentation <http://people.csail.mit.edu/hubert/pyaudio/docs/>`__ for more details.
  50. The microphone audio is recorded in chunks of ``chunk_size`` samples, at a rate of ``sample_rate`` samples per second (Hertz).
  51. Higher ``sample_rate`` values result in better audio quality, but also more bandwidth (and therefore, slower recognition). Additionally, some machines, such as some Raspberry Pi models, can't keep up if this value is too high.
  52. Higher ``chunk_size`` values help avoid triggering on rapidly changing ambient noise, but also makes detection less sensitive. This value, generally, should be left at its default.
  53. """
  54. def __init__(self, device_index=None, sample_rate=16000, chunk_size=1024):
  55. # set up PyAudio
  56. self.pyaudio_module = self.get_pyaudio()
  57. assert device_index is None or isinstance(device_index, int), "Device index must be None or an integer"
  58. if device_index is not None: # ensure device index is in range
  59. audio = self.pyaudio_module.PyAudio()
  60. try:
  61. count = audio.get_device_count() # obtain device count
  62. except:
  63. audio.terminate()
  64. raise
  65. assert 0 <= device_index < count, "Device index out of range ({} devices available; device index should be between 0 and {} inclusive)".format(count, count - 1)
  66. assert isinstance(sample_rate, int) and sample_rate > 0, "Sample rate must be a positive integer"
  67. assert isinstance(chunk_size, int) and chunk_size > 0, "Chunk size must be a positive integer"
  68. self.device_index = device_index
  69. self.format = self.pyaudio_module.paInt16 # 16-bit int sampling
  70. self.SAMPLE_WIDTH = self.pyaudio_module.get_sample_size(self.format) # size of each sample
  71. self.SAMPLE_RATE = sample_rate # sampling rate in Hertz
  72. self.CHUNK = chunk_size # number of frames stored in each buffer
  73. self.audio = None
  74. self.stream = None
  75. @staticmethod
  76. def get_pyaudio():
  77. """
  78. Imports the pyaudio module and checks its version. Throws exceptions if pyaudio can't be found or a wrong version is installed
  79. """
  80. try:
  81. import pyaudio
  82. except ImportError:
  83. raise AttributeError("Could not find PyAudio; check installation")
  84. from distutils.version import LooseVersion
  85. if LooseVersion(pyaudio.__version__) < LooseVersion("0.2.9"):
  86. raise AttributeError("PyAudio 0.2.9 or later is required (found version {})".format(pyaudio.__version__))
  87. return pyaudio
  88. @staticmethod
  89. def list_microphone_names():
  90. """
  91. Returns a list of the names of all available microphones. For microphones where the name can't be retrieved, the list entry contains ``None`` instead.
  92. The index of each microphone's name is the same as its device index when creating a ``Microphone`` instance - indices in this list can be used as values of ``device_index``.
  93. """
  94. audio = Microphone.get_pyaudio().PyAudio()
  95. try:
  96. result = []
  97. for i in range(audio.get_device_count()):
  98. device_info = audio.get_device_info_by_index(i)
  99. result.append(device_info.get("name"))
  100. finally:
  101. audio.terminate()
  102. return result
  103. def __enter__(self):
  104. assert self.stream is None, "This audio source is already inside a context manager"
  105. self.audio = self.pyaudio_module.PyAudio()
  106. try:
  107. self.stream = Microphone.MicrophoneStream(
  108. self.audio.open(
  109. input_device_index=self.device_index, channels=1,
  110. format=self.format, rate=self.SAMPLE_RATE, frames_per_buffer=self.CHUNK,
  111. input=True, # stream is an input stream
  112. )
  113. )
  114. except:
  115. self.audio.terminate()
  116. raise
  117. return self
  118. def __exit__(self, exc_type, exc_value, traceback):
  119. try:
  120. self.stream.close()
  121. finally:
  122. self.stream = None
  123. self.audio.terminate()
  124. class MicrophoneStream(object):
  125. def __init__(self, pyaudio_stream):
  126. self.pyaudio_stream = pyaudio_stream
  127. def read(self, size):
  128. return self.pyaudio_stream.read(size, exception_on_overflow=False)
  129. def close(self):
  130. try:
  131. # sometimes, if the stream isn't stopped, closing the stream throws an exception
  132. if not self.pyaudio_stream.is_stopped():
  133. self.pyaudio_stream.stop_stream()
  134. finally:
  135. self.pyaudio_stream.close()
  136. class AudioFile(AudioSource):
  137. """
  138. Creates a new ``AudioFile`` instance given a WAV/AIFF/FLAC audio file ``filename_or_fileobject``. Subclass of ``AudioSource``.
  139. If ``filename_or_fileobject`` is a string, then it is interpreted as a path to an audio file on the filesystem. Otherwise, ``filename_or_fileobject`` should be a file-like object such as ``io.BytesIO`` or similar.
  140. Note that functions that read from the audio (such as ``recognizer_instance.record`` or ``recognizer_instance.listen``) will move ahead in the stream. For example, if you execute ``recognizer_instance.record(audiofile_instance, duration=10)`` twice, the first time it will return the first 10 seconds of audio, and the second time it will return the 10 seconds of audio right after that. This is always reset to the beginning when entering an ``AudioFile`` context.
  141. WAV files must be in PCM/LPCM format; WAVE_FORMAT_EXTENSIBLE and compressed WAV are not supported and may result in undefined behaviour.
  142. Both AIFF and AIFF-C (compressed AIFF) formats are supported.
  143. FLAC files must be in native FLAC format; OGG-FLAC is not supported and may result in undefined behaviour.
  144. """
  145. def __init__(self, filename_or_fileobject):
  146. if str is bytes: # Python 2 - if a file path is specified, it must either be a ``str`` instance or a ``unicode`` instance
  147. assert isinstance(filename_or_fileobject, (type(""), type(u""))) or hasattr(filename_or_fileobject, "read"), "Given audio file must be a filename string or a file-like object"
  148. else: # Python 3 - if a file path is specified, it must be a ``str`` instance
  149. assert isinstance(filename_or_fileobject, str) or hasattr(filename_or_fileobject, "read"), "Given audio file must be a filename string or a file-like object"
  150. self.filename_or_fileobject = filename_or_fileobject
  151. self.stream = None
  152. self.DURATION = None
  153. def __enter__(self):
  154. assert self.stream is None, "This audio source is already inside a context manager"
  155. try:
  156. # attempt to read the file as WAV
  157. self.audio_reader = wave.open(self.filename_or_fileobject, "rb")
  158. self.little_endian = True # RIFF WAV is a little-endian format (most ``audioop`` operations assume that the frames are stored in little-endian form)
  159. except wave.Error:
  160. try:
  161. # attempt to read the file as AIFF
  162. self.audio_reader = aifc.open(self.filename_or_fileobject, "rb")
  163. self.little_endian = False # AIFF is a big-endian format
  164. except aifc.Error:
  165. # attempt to read the file as FLAC
  166. if hasattr(self.filename_or_fileobject, "read"):
  167. flac_data = self.filename_or_fileobject.read()
  168. else:
  169. with open(self.filename_or_fileobject, "rb") as f: flac_data = f.read()
  170. # run the FLAC converter with the FLAC data to get the AIFF data
  171. flac_converter = get_flac_converter()
  172. process = subprocess.Popen([
  173. flac_converter,
  174. "--stdout", "--totally-silent", # put the resulting AIFF file in stdout, and make sure it's not mixed with any program output
  175. "--decode", "--force-aiff-format", # decode the FLAC file into an AIFF file
  176. "-", # the input FLAC file contents will be given in stdin
  177. ], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
  178. aiff_data, stderr = process.communicate(flac_data)
  179. aiff_file = io.BytesIO(aiff_data)
  180. try:
  181. self.audio_reader = aifc.open(aiff_file, "rb")
  182. except aifc.Error:
  183. raise ValueError("Audio file could not be read as PCM WAV, AIFF/AIFF-C, or Native FLAC; check if file is corrupted or in another format")
  184. self.little_endian = False # AIFF is a big-endian format
  185. assert 1 <= self.audio_reader.getnchannels() <= 2, "Audio must be mono or stereo"
  186. self.SAMPLE_WIDTH = self.audio_reader.getsampwidth()
  187. # 24-bit audio needs some special handling for old Python versions (workaround for https://bugs.python.org/issue12866)
  188. samples_24_bit_pretending_to_be_32_bit = False
  189. if self.SAMPLE_WIDTH == 3: # 24-bit audio
  190. try: audioop.bias(b"", self.SAMPLE_WIDTH, 0) # test whether this sample width is supported (for example, ``audioop`` in Python 3.3 and below don't support sample width 3, while Python 3.4+ do)
  191. except audioop.error: # this version of audioop doesn't support 24-bit audio (probably Python 3.3 or less)
  192. samples_24_bit_pretending_to_be_32_bit = True # while the ``AudioFile`` instance will outwardly appear to be 32-bit, it will actually internally be 24-bit
  193. self.SAMPLE_WIDTH = 4 # the ``AudioFile`` instance should present itself as a 32-bit stream now, since we'll be converting into 32-bit on the fly when reading
  194. self.SAMPLE_RATE = self.audio_reader.getframerate()
  195. self.CHUNK = 4096
  196. self.FRAME_COUNT = self.audio_reader.getnframes()
  197. self.DURATION = self.FRAME_COUNT / float(self.SAMPLE_RATE)
  198. self.stream = AudioFile.AudioFileStream(self.audio_reader, self.little_endian, samples_24_bit_pretending_to_be_32_bit)
  199. return self
  200. def __exit__(self, exc_type, exc_value, traceback):
  201. if not hasattr(self.filename_or_fileobject, "read"): # only close the file if it was opened by this class in the first place (if the file was originally given as a path)
  202. self.audio_reader.close()
  203. self.stream = None
  204. self.DURATION = None
  205. class AudioFileStream(object):
  206. def __init__(self, audio_reader, little_endian, samples_24_bit_pretending_to_be_32_bit):
  207. self.audio_reader = audio_reader # an audio file object (e.g., a `wave.Wave_read` instance)
  208. self.little_endian = little_endian # whether the audio data is little-endian (when working with big-endian things, we'll have to convert it to little-endian before we process it)
  209. self.samples_24_bit_pretending_to_be_32_bit = samples_24_bit_pretending_to_be_32_bit # this is true if the audio is 24-bit audio, but 24-bit audio isn't supported, so we have to pretend that this is 32-bit audio and convert it on the fly
  210. def read(self, size=-1):
  211. buffer = self.audio_reader.readframes(self.audio_reader.getnframes() if size == -1 else size)
  212. if not isinstance(buffer, bytes): buffer = b"" # workaround for https://bugs.python.org/issue24608
  213. sample_width = self.audio_reader.getsampwidth()
  214. if not self.little_endian: # big endian format, convert to little endian on the fly
  215. if hasattr(audioop, "byteswap"): # ``audioop.byteswap`` was only added in Python 3.4 (incidentally, that also means that we don't need to worry about 24-bit audio being unsupported, since Python 3.4+ always has that functionality)
  216. buffer = audioop.byteswap(buffer, sample_width)
  217. else: # manually reverse the bytes of each sample, which is slower but works well enough as a fallback
  218. buffer = buffer[sample_width - 1::-1] + b"".join(buffer[i + sample_width:i:-1] for i in range(sample_width - 1, len(buffer), sample_width))
  219. # workaround for https://bugs.python.org/issue12866
  220. if self.samples_24_bit_pretending_to_be_32_bit: # we need to convert samples from 24-bit to 32-bit before we can process them with ``audioop`` functions
  221. buffer = b"".join("\x00" + buffer[i:i + sample_width] for i in range(0, len(buffer), sample_width)) # since we're in little endian, we prepend a zero byte to each 24-bit sample to get a 32-bit sample
  222. if self.audio_reader.getnchannels() != 1: # stereo audio
  223. buffer = audioop.tomono(buffer, sample_width, 1, 1) # convert stereo audio data to mono
  224. return buffer
  225. class AudioData(object):
  226. """
  227. Creates a new ``AudioData`` instance, which represents mono audio data.
  228. The raw audio data is specified by ``frame_data``, which is a sequence of bytes representing audio samples. This is the frame data structure used by the PCM WAV format.
  229. The width of each sample, in bytes, is specified by ``sample_width``. Each group of ``sample_width`` bytes represents a single audio sample.
  230. The audio data is assumed to have a sample rate of ``sample_rate`` samples per second (Hertz).
  231. Usually, instances of this class are obtained from ``recognizer_instance.record`` or ``recognizer_instance.listen``, or in the callback for ``recognizer_instance.listen_in_background``, rather than instantiating them directly.
  232. """
  233. def __init__(self, frame_data, sample_rate, sample_width):
  234. assert sample_rate > 0, "Sample rate must be a positive integer"
  235. assert sample_width % 1 == 0 and 1 <= sample_width <= 4, "Sample width must be between 1 and 4 inclusive"
  236. self.frame_data = frame_data
  237. self.sample_rate = sample_rate
  238. self.sample_width = int(sample_width)
  239. def get_raw_data(self, convert_rate=None, convert_width=None):
  240. """
  241. Returns a byte string representing the raw frame data for the audio represented by the ``AudioData`` instance.
  242. If ``convert_rate`` is specified and the audio sample rate is not ``convert_rate`` Hz, the resulting audio is resampled to match.
  243. If ``convert_width`` is specified and the audio samples are not ``convert_width`` bytes each, the resulting audio is converted to match.
  244. Writing these bytes directly to a file results in a valid `RAW/PCM audio file <https://en.wikipedia.org/wiki/Raw_audio_format>`__.
  245. """
  246. assert convert_rate is None or convert_rate > 0, "Sample rate to convert to must be a positive integer"
  247. assert convert_width is None or (convert_width % 1 == 0 and 1 <= convert_width <= 4), "Sample width to convert to must be between 1 and 4 inclusive"
  248. raw_data = self.frame_data
  249. # make sure unsigned 8-bit audio (which uses unsigned samples) is handled like higher sample width audio (which uses signed samples)
  250. if self.sample_width == 1:
  251. raw_data = audioop.bias(raw_data, 1, -128) # subtract 128 from every sample to make them act like signed samples
  252. # resample audio at the desired rate if specified
  253. if convert_rate is not None and self.sample_rate != convert_rate:
  254. raw_data, _ = audioop.ratecv(raw_data, self.sample_width, 1, self.sample_rate, convert_rate, None)
  255. # convert samples to desired sample width if specified
  256. if convert_width is not None and self.sample_width != convert_width:
  257. if convert_width == 3: # we're converting the audio into 24-bit (workaround for https://bugs.python.org/issue12866)
  258. raw_data = audioop.lin2lin(raw_data, self.sample_width, 4) # convert audio into 32-bit first, which is always supported
  259. try: audioop.bias(b"", 3, 0) # test whether 24-bit audio is supported (for example, ``audioop`` in Python 3.3 and below don't support sample width 3, while Python 3.4+ do)
  260. except audioop.error: # this version of audioop doesn't support 24-bit audio (probably Python 3.3 or less)
  261. raw_data = b"".join(raw_data[i + 1:i + 4] for i in range(0, len(raw_data), 4)) # since we're in little endian, we discard the first byte from each 32-bit sample to get a 24-bit sample
  262. else: # 24-bit audio fully supported, we don't need to shim anything
  263. raw_data = audioop.lin2lin(raw_data, self.sample_width, convert_width)
  264. else:
  265. raw_data = audioop.lin2lin(raw_data, self.sample_width, convert_width)
  266. # if the output is 8-bit audio with unsigned samples, convert the samples we've been treating as signed to unsigned again
  267. if convert_width == 1:
  268. raw_data = audioop.bias(raw_data, 1, 128) # add 128 to every sample to make them act like unsigned samples again
  269. return raw_data
  270. def get_wav_data(self, convert_rate=None, convert_width=None):
  271. """
  272. Returns a byte string representing the contents of a WAV file containing the audio represented by the ``AudioData`` instance.
  273. If ``convert_width`` is specified and the audio samples are not ``convert_width`` bytes each, the resulting audio is converted to match.
  274. If ``convert_rate`` is specified and the audio sample rate is not ``convert_rate`` Hz, the resulting audio is resampled to match.
  275. Writing these bytes directly to a file results in a valid `WAV file <https://en.wikipedia.org/wiki/WAV>`__.
  276. """
  277. raw_data = self.get_raw_data(convert_rate, convert_width)
  278. sample_rate = self.sample_rate if convert_rate is None else convert_rate
  279. sample_width = self.sample_width if convert_width is None else convert_width
  280. # generate the WAV file contents
  281. with io.BytesIO() as wav_file:
  282. wav_writer = wave.open(wav_file, "wb")
  283. try: # note that we can't use context manager, since that was only added in Python 3.4
  284. wav_writer.setframerate(sample_rate)
  285. wav_writer.setsampwidth(sample_width)
  286. wav_writer.setnchannels(1)
  287. wav_writer.writeframes(raw_data)
  288. wav_data = wav_file.getvalue()
  289. finally: # make sure resources are cleaned up
  290. wav_writer.close()
  291. return wav_data
  292. def get_aiff_data(self, convert_rate=None, convert_width=None):
  293. """
  294. Returns a byte string representing the contents of an AIFF-C file containing the audio represented by the ``AudioData`` instance.
  295. If ``convert_width`` is specified and the audio samples are not ``convert_width`` bytes each, the resulting audio is converted to match.
  296. If ``convert_rate`` is specified and the audio sample rate is not ``convert_rate`` Hz, the resulting audio is resampled to match.
  297. Writing these bytes directly to a file results in a valid `AIFF-C file <https://en.wikipedia.org/wiki/Audio_Interchange_File_Format>`__.
  298. """
  299. raw_data = self.get_raw_data(convert_rate, convert_width)
  300. sample_rate = self.sample_rate if convert_rate is None else convert_rate
  301. sample_width = self.sample_width if convert_width is None else convert_width
  302. # the AIFF format is big-endian, so we need to covnert the little-endian raw data to big-endian
  303. if hasattr(audioop, "byteswap"): # ``audioop.byteswap`` was only added in Python 3.4
  304. raw_data = audioop.byteswap(raw_data, sample_width)
  305. else: # manually reverse the bytes of each sample, which is slower but works well enough as a fallback
  306. raw_data = raw_data[sample_width - 1::-1] + b"".join(raw_data[i + sample_width:i:-1] for i in range(sample_width - 1, len(raw_data), sample_width))
  307. # generate the AIFF-C file contents
  308. with io.BytesIO() as aiff_file:
  309. aiff_writer = aifc.open(aiff_file, "wb")
  310. try: # note that we can't use context manager, since that was only added in Python 3.4
  311. aiff_writer.setframerate(sample_rate)
  312. aiff_writer.setsampwidth(sample_width)
  313. aiff_writer.setnchannels(1)
  314. aiff_writer.writeframes(raw_data)
  315. aiff_data = aiff_file.getvalue()
  316. finally: # make sure resources are cleaned up
  317. aiff_writer.close()
  318. return aiff_data
  319. def get_flac_data(self, convert_rate=None, convert_width=None):
  320. """
  321. Returns a byte string representing the contents of a FLAC file containing the audio represented by the ``AudioData`` instance.
  322. Note that 32-bit FLAC is not supported. If the audio data is 32-bit and ``convert_width`` is not specified, then the resulting FLAC will be a 24-bit FLAC.
  323. If ``convert_rate`` is specified and the audio sample rate is not ``convert_rate`` Hz, the resulting audio is resampled to match.
  324. If ``convert_width`` is specified and the audio samples are not ``convert_width`` bytes each, the resulting audio is converted to match.
  325. Writing these bytes directly to a file results in a valid `FLAC file <https://en.wikipedia.org/wiki/FLAC>`__.
  326. """
  327. assert convert_width is None or (convert_width % 1 == 0 and 1 <= convert_width <= 3), "Sample width to convert to must be between 1 and 3 inclusive"
  328. if self.sample_width > 3 and convert_width is None: # resulting WAV data would be 32-bit, which is not convertable to FLAC using our encoder
  329. convert_width = 3 # the largest supported sample width is 24-bit, so we'll limit the sample width to that
  330. # run the FLAC converter with the WAV data to get the FLAC data
  331. wav_data = self.get_wav_data(convert_rate, convert_width)
  332. flac_converter = get_flac_converter()
  333. process = subprocess.Popen([
  334. flac_converter,
  335. "--stdout", "--totally-silent", # put the resulting FLAC file in stdout, and make sure it's not mixed with any program output
  336. "--best", # highest level of compression available
  337. "-", # the input FLAC file contents will be given in stdin
  338. ], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
  339. flac_data, stderr = process.communicate(wav_data)
  340. return flac_data
  341. class Recognizer(AudioSource):
  342. def __init__(self):
  343. """
  344. Creates a new ``Recognizer`` instance, which represents a collection of speech recognition functionality.
  345. """
  346. self.energy_threshold = 300 # minimum audio energy to consider for recording
  347. self.dynamic_energy_threshold = True
  348. self.dynamic_energy_adjustment_damping = 0.15
  349. self.dynamic_energy_ratio = 1.5
  350. self.pause_threshold = 0.8 # seconds of non-speaking audio before a phrase is considered complete
  351. self.operation_timeout = None # seconds after an internal operation (e.g., an API request) starts before it times out, or ``None`` for no timeout
  352. self.phrase_threshold = 0.3 # minimum seconds of speaking audio before we consider the speaking audio a phrase - values below this are ignored (for filtering out clicks and pops)
  353. self.non_speaking_duration = 0.5 # seconds of non-speaking audio to keep on both sides of the recording
  354. def record(self, source, duration=None, offset=None):
  355. """
  356. Records up to ``duration`` seconds of audio from ``source`` (an ``AudioSource`` instance) starting at ``offset`` (or at the beginning if not specified) into an ``AudioData`` instance, which it returns.
  357. If ``duration`` is not specified, then it will record until there is no more audio input.
  358. """
  359. assert isinstance(source, AudioSource), "Source must be an audio source"
  360. assert source.stream is not None, "Audio source must be entered before recording, see documentation for ``AudioSource``; are you using ``source`` outside of a ``with`` statement?"
  361. frames = io.BytesIO()
  362. seconds_per_buffer = (source.CHUNK + 0.0) / source.SAMPLE_RATE
  363. elapsed_time = 0
  364. offset_time = 0
  365. offset_reached = False
  366. while True: # loop for the total number of chunks needed
  367. if offset and not offset_reached:
  368. offset_time += seconds_per_buffer
  369. if offset_time > offset:
  370. offset_reached = True
  371. buffer = source.stream.read(source.CHUNK)
  372. if len(buffer) == 0: break
  373. if offset_reached or not offset:
  374. elapsed_time += seconds_per_buffer
  375. if duration and elapsed_time > duration: break
  376. frames.write(buffer)
  377. frame_data = frames.getvalue()
  378. frames.close()
  379. return AudioData(frame_data, source.SAMPLE_RATE, source.SAMPLE_WIDTH)
  380. def adjust_for_ambient_noise(self, source, duration=1):
  381. """
  382. Adjusts the energy threshold dynamically using audio from ``source`` (an ``AudioSource`` instance) to account for ambient noise.
  383. Intended to calibrate the energy threshold with the ambient energy level. Should be used on periods of audio without speech - will stop early if any speech is detected.
  384. The ``duration`` parameter is the maximum number of seconds that it will dynamically adjust the threshold for before returning. This value should be at least 0.5 in order to get a representative sample of the ambient noise.
  385. """
  386. assert isinstance(source, AudioSource), "Source must be an audio source"
  387. assert source.stream is not None, "Audio source must be entered before adjusting, see documentation for ``AudioSource``; are you using ``source`` outside of a ``with`` statement?"
  388. assert self.pause_threshold >= self.non_speaking_duration >= 0
  389. seconds_per_buffer = (source.CHUNK + 0.0) / source.SAMPLE_RATE
  390. elapsed_time = 0
  391. # adjust energy threshold until a phrase starts
  392. while True:
  393. elapsed_time += seconds_per_buffer
  394. if elapsed_time > duration: break
  395. buffer = source.stream.read(source.CHUNK)
  396. energy = audioop.rms(buffer, source.SAMPLE_WIDTH) # energy of the audio signal
  397. # dynamically adjust the energy threshold using asymmetric weighted average
  398. damping = self.dynamic_energy_adjustment_damping ** seconds_per_buffer # account for different chunk sizes and rates
  399. target_energy = energy * self.dynamic_energy_ratio
  400. self.energy_threshold = self.energy_threshold * damping + target_energy * (1 - damping)
  401. def listen(self, source, timeout=None, phrase_time_limit=None):
  402. """
  403. Records a single phrase from ``source`` (an ``AudioSource`` instance) into an ``AudioData`` instance, which it returns.
  404. This is done by waiting until the audio has an energy above ``recognizer_instance.energy_threshold`` (the user has started speaking), and then recording until it encounters ``recognizer_instance.pause_threshold`` seconds of non-speaking or there is no more audio input. The ending silence is not included.
  405. The ``timeout`` parameter is the maximum number of seconds that this will wait for a phrase to start before giving up and throwing an ``speech_recognition.WaitTimeoutError`` exception. If ``timeout`` is ``None``, there will be no wait timeout.
  406. The ``phrase_time_limit`` parameter is the maximum number of seconds that this will allow a phrase to continue before stopping and returning the part of the phrase processed before the time limit was reached. The resulting audio will be the phrase cut off at the time limit. If ``phrase_timeout`` is ``None``, there will be no phrase time limit.
  407. This operation will always complete within ``timeout + phrase_timeout`` seconds if both are numbers, either by returning the audio data, or by raising an exception.
  408. """
  409. assert isinstance(source, AudioSource), "Source must be an audio source"
  410. assert source.stream is not None, "Audio source must be entered before listening, see documentation for ``AudioSource``; are you using ``source`` outside of a ``with`` statement?"
  411. assert self.pause_threshold >= self.non_speaking_duration >= 0
  412. seconds_per_buffer = (source.CHUNK + 0.0) / source.SAMPLE_RATE
  413. pause_buffer_count = int(math.ceil(self.pause_threshold / seconds_per_buffer)) # number of buffers of non-speaking audio during a phrase, before the phrase should be considered complete
  414. phrase_buffer_count = int(math.ceil(self.phrase_threshold / seconds_per_buffer)) # minimum number of buffers of speaking audio before we consider the speaking audio a phrase
  415. non_speaking_buffer_count = int(math.ceil(self.non_speaking_duration / seconds_per_buffer)) # maximum number of buffers of non-speaking audio to retain before and after a phrase
  416. logging.info((seconds_per_buffer, pause_buffer_count))
  417. logging.info((source.CHUNK, source.SAMPLE_RATE))
  418. # read audio input for phrases until there is a phrase that is long enough
  419. elapsed_time = 0 # number of seconds of audio read
  420. buffer = b"" # an empty buffer means that the stream has ended and there is no data left to read
  421. while True:
  422. frames = collections.deque()
  423. # store audio input until the phrase starts
  424. while True:
  425. # handle waiting too long for phrase by raising an exception
  426. elapsed_time += seconds_per_buffer
  427. if timeout and elapsed_time > timeout:
  428. raise WaitTimeoutError("listening timed out while waiting for phrase to start")
  429. buffer = source.stream.read(source.CHUNK)
  430. if len(buffer) == 0: break # reached end of the stream
  431. frames.append(buffer)
  432. if len(frames) > non_speaking_buffer_count: # ensure we only keep the needed amount of non-speaking buffers
  433. frames.popleft()
  434. # detect whether speaking has started on audio input
  435. energy = audioop.rms(buffer, source.SAMPLE_WIDTH) # energy of the audio signal
  436. if energy > self.energy_threshold: break
  437. # dynamically adjust the energy threshold using asymmetric weighted average
  438. if self.dynamic_energy_threshold:
  439. damping = self.dynamic_energy_adjustment_damping ** seconds_per_buffer # account for different chunk sizes and rates
  440. target_energy = energy * self.dynamic_energy_ratio
  441. self.energy_threshold = self.energy_threshold * damping + target_energy * (1 - damping)
  442. logging.info('Waiting for start of phrase (energy: %i; energy threshold: %i)', energy, self.energy_threshold)
  443. # read audio input until the phrase ends
  444. pause_count, phrase_count = 0, 0
  445. phrase_start_time = elapsed_time
  446. while True:
  447. # handle phrase being too long by cutting off the audio
  448. elapsed_time += seconds_per_buffer
  449. if phrase_time_limit and elapsed_time - phrase_start_time > phrase_time_limit:
  450. break
  451. buffer = source.stream.read(source.CHUNK)
  452. if len(buffer) == 0: break # reached end of the stream
  453. frames.append(buffer)
  454. phrase_count += 1
  455. # check if speaking has stopped for longer than the pause threshold on the audio input
  456. energy = audioop.rms(buffer, source.SAMPLE_WIDTH) # unit energy of the audio signal within the buffer
  457. if energy > self.energy_threshold:
  458. pause_count = 0
  459. else:
  460. pause_count += 1
  461. if pause_count > pause_buffer_count: # end of the phrase
  462. break
  463. logging.info('Waiting for end of phrase (energy: %i; energy threshold: %i)', energy, self.energy_threshold)
  464. logging.info((phrase_count, pause_count, phrase_buffer_count, len(buffer)))
  465. # check how long the detected phrase is, and retry listening if the phrase is too short
  466. if phrase_count - pause_count >= phrase_buffer_count or len(buffer) == 0: break # phrase is long enough or we've reached the end of the stream, so stop listening
  467. # obtain frame data
  468. for i in range(pause_count - non_speaking_buffer_count): frames.pop() # remove extra non-speaking frames at the end
  469. frame_data = b"".join(list(frames))
  470. return AudioData(frame_data, source.SAMPLE_RATE, source.SAMPLE_WIDTH)
  471. def listen_in_background(self, source, callback, phrase_time_limit=None):
  472. """
  473. Spawns a thread to repeatedly record phrases from ``source`` (an ``AudioSource`` instance) into an ``AudioData`` instance and call ``callback`` with that ``AudioData`` instance as soon as each phrase are detected.
  474. Returns a function object that, when called, requests that the background listener thread stop, and waits until it does before returning. The background thread is a daemon and will not stop the program from exiting if there are no other non-daemon threads.
  475. Phrase recognition uses the exact same mechanism as ``recognizer_instance.listen(source)``. The ``phrase_time_limit`` parameter works in the same way as the ``phrase_time_limit`` parameter for ``recognizer_instance.listen(source)``, as well.
  476. The ``callback`` parameter is a function that should accept two parameters - the ``recognizer_instance``, and an ``AudioData`` instance representing the captured audio. Note that ``callback`` function will be called from a non-main thread.
  477. """
  478. assert isinstance(source, AudioSource), "Source must be an audio source"
  479. running = [True]
  480. def threaded_listen():
  481. with source as s:
  482. while running[0]:
  483. try: # listen for 1 second, then check again if the stop function has been called
  484. audio = self.listen(s, 1)
  485. except WaitTimeoutError: # listening timed out, just try again
  486. pass
  487. else:
  488. if running[0]: callback(self, audio)
  489. def stopper():
  490. running[0] = False
  491. listener_thread.join() # block until the background thread is done, which can be up to 1 second
  492. listener_thread = threading.Thread(target=threaded_listen)
  493. listener_thread.daemon = True
  494. listener_thread.start()
  495. return stopper
  496. def recognize_sphinx(self, audio_data, language="en-US", keyword_entries=None, show_all=False):
  497. """
  498. Performs speech recognition on ``audio_data`` (an ``AudioData`` instance), using CMU Sphinx.
  499. The recognition language is determined by ``language``, an RFC5646 language tag like ``"en-US"`` or ``"en-GB"``, defaulting to US English. Out of the box, only ``en-US`` is supported. See `Notes on using `PocketSphinx <https://github.com/Uberi/speech_recognition/blob/master/reference/pocketsphinx.rst>`__ for information about installing other languages. This document is also included under ``reference/pocketsphinx.rst``.
  500. If specified, the keywords to search for are determined by ``keyword_entries``, an iterable of tuples of the form ``(keyword, sensitivity)``, where ``keyword`` is a phrase, and ``sensitivity`` is how sensitive to this phrase the recognizer should be, on a scale of 0 (very insensitive, more false negatives) to 1 (very sensitive, more false positives) inclusive. If not specified or ``None``, no keywords are used and Sphinx will simply transcribe whatever words it recognizes. Specifying ``keyword_entries`` is more accurate than just looking for those same keywords in non-keyword-based transcriptions, because Sphinx knows specifically what sounds to look for.
  501. Returns the most likely transcription if ``show_all`` is false (the default). Otherwise, returns the Sphinx ``pocketsphinx.pocketsphinx.Decoder`` object resulting from the recognition.
  502. Raises a ``speech_recognition.UnknownValueError`` exception if the speech is unintelligible. Raises a ``speech_recognition.RequestError`` exception if there are any issues with the Sphinx installation.
  503. """
  504. assert isinstance(audio_data, AudioData), "``audio_data`` must be audio data"
  505. assert isinstance(language, str), "``language`` must be a string"
  506. assert keyword_entries is None or all(isinstance(keyword, str) and 0 <= sensitivity <= 1 for keyword, sensitivity in keyword_entries), "``keyword_entries`` must be ``None`` or a list of pairs of strings and numbers between 0 and 1"
  507. # import the PocketSphinx speech recognition module
  508. try:
  509. from pocketsphinx import pocketsphinx
  510. except ImportError:
  511. raise RequestError("missing PocketSphinx module: ensure that PocketSphinx is set up correctly.")
  512. except ValueError:
  513. raise RequestError("bad PocketSphinx installation detected; make sure you have PocketSphinx version 0.0.9 or better.")
  514. language_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), "pocketsphinx-data", language)
  515. if not os.path.isdir(language_directory):
  516. raise RequestError("missing PocketSphinx language data directory: \"{}\"".format(language_directory))
  517. acoustic_parameters_directory = os.path.join(language_directory, "acoustic-model")
  518. if not os.path.isdir(acoustic_parameters_directory):
  519. raise RequestError("missing PocketSphinx language model parameters directory: \"{}\"".format(acoustic_parameters_directory))
  520. language_model_file = os.path.join(language_directory, "language-model.lm.bin")
  521. if not os.path.isfile(language_model_file):
  522. raise RequestError("missing PocketSphinx language model file: \"{}\"".format(language_model_file))
  523. phoneme_dictionary_file = os.path.join(language_directory, "pronounciation-dictionary.dict")
  524. if not os.path.isfile(phoneme_dictionary_file):
  525. raise RequestError("missing PocketSphinx phoneme dictionary file: \"{}\"".format(phoneme_dictionary_file))
  526. # create decoder object
  527. config = pocketsphinx.Decoder.default_config()
  528. config.set_string("-hmm", acoustic_parameters_directory) # set the path of the hidden Markov model (HMM) parameter files
  529. config.set_string("-lm", language_model_file)
  530. config.set_string("-dict", phoneme_dictionary_file)
  531. config.set_string("-logfn", os.devnull) # disable logging (logging causes unwanted output in terminal)
  532. decoder = pocketsphinx.Decoder(config)
  533. # obtain audio data
  534. raw_data = audio_data.get_raw_data(convert_rate=16000, convert_width=2) # the included language models require audio to be 16-bit mono 16 kHz in little-endian format
  535. # obtain recognition results
  536. if keyword_entries is not None: # explicitly specified set of keywords
  537. with tempfile_TemporaryDirectory() as temp_directory:
  538. # generate a keywords file - Sphinx documentation recommendeds sensitivities between 1e-50 and 1e-5
  539. keywords_path = os.path.join(temp_directory, "keyphrases.txt")
  540. with open(keywords_path, "w") as f:
  541. f.writelines("{} /1e{}/\n".format(keyword, 100 * sensitivity - 110) for keyword, sensitivity in keyword_entries)
  542. # perform the speech recognition with the keywords file (this is inside the context manager so the file isn;t deleted until we're done)
  543. decoder.set_kws("keywords", keywords_path)
  544. decoder.set_search("keywords")
  545. decoder.start_utt() # begin utterance processing
  546. decoder.process_raw(raw_data, False, True) # process audio data with recognition enabled (no_search = False), as a full utterance (full_utt = True)
  547. decoder.end_utt() # stop utterance processing
  548. else: # no keywords, perform freeform recognition
  549. decoder.start_utt() # begin utterance processing
  550. decoder.process_raw(raw_data, False, True) # process audio data with recognition enabled (no_search = False), as a full utterance (full_utt = True)
  551. decoder.end_utt() # stop utterance processing
  552. if show_all: return decoder
  553. # return results
  554. hypothesis = decoder.hyp()
  555. if hypothesis is not None: return hypothesis.hypstr
  556. raise UnknownValueError() # no transcriptions available
  557. def recognize_google(self, audio_data, key=None, language="en-US", show_all=False):
  558. """
  559. Performs speech recognition on ``audio_data`` (an ``AudioData`` instance), using the Google Speech Recognition API.
  560. The Google Speech Recognition API key is specified by ``key``. If not specified, it uses a generic key that works out of the box. This should generally be used for personal or testing purposes only, as it **may be revoked by Google at any time**.
  561. To obtain your own API key, simply following the steps on the `API Keys <http://www.chromium.org/developers/how-tos/api-keys>`__ page at the Chromium Developers site. In the Google Developers Console, Google Speech Recognition is listed as "Speech API".
  562. The recognition language is determined by ``language``, an RFC5646 language tag like ``"en-US"`` (US English) or ``"fr-FR"`` (International French), defaulting to US English. A list of supported language values can be found in this `StackOverflow answer <http://stackoverflow.com/a/14302134>`__.
  563. Returns the most likely transcription if ``show_all`` is false (the default). Otherwise, returns the raw API response as a JSON dictionary.
  564. Raises a ``speech_recognition.UnknownValueError`` exception if the speech is unintelligible. Raises a ``speech_recognition.RequestError`` exception if the speech recognition operation failed, if the key isn't valid, or if there is no internet connection.
  565. """
  566. assert isinstance(audio_data, AudioData), "``audio_data`` must be audio data"
  567. assert key is None or isinstance(key, str), "``key`` must be ``None`` or a string"
  568. assert isinstance(language, str), "``language`` must be a string"
  569. flac_data = audio_data.get_flac_data(
  570. convert_rate=None if audio_data.sample_rate >= 8000 else 8000, # audio samples must be at least 8 kHz
  571. convert_width=2 # audio samples must be 16-bit
  572. )
  573. if key is None: key = "AIzaSyBOti4mM-6x9WDnZIjIeyEU21OpBXqWBgw"
  574. url = "http://www.google.com/speech-api/v2/recognize?{}".format(urlencode({
  575. "client": "chromium",
  576. "lang": language,
  577. "key": key,
  578. }))
  579. request = Request(url, data=flac_data, headers={"Content-Type": "audio/x-flac; rate={}".format(audio_data.sample_rate)})
  580. # obtain audio transcription results
  581. try:
  582. response = urlopen(request, timeout=self.operation_timeout)
  583. except HTTPError as e:
  584. raise RequestError("recognition request failed: {}".format(e.reason))
  585. except URLError as e:
  586. raise RequestError("recognition connection failed: {}".format(e.reason))
  587. response_text = response.read().decode("utf-8")
  588. # ignore any blank blocks
  589. actual_result = {}
  590. for line in response_text.split("\n"):
  591. if not line: continue
  592. result = json.loads(line)["result"]
  593. if len(result) != 0:
  594. actual_result = result[0]
  595. break
  596. # return results
  597. if show_all: return actual_result
  598. if len(actual_result.get("alternative", [])) == 0: raise UnknownValueError()
  599. # return alternative with highest confidence score
  600. best_hypothesis = max(actual_result["alternative"], key=lambda alternative: alternative.get("confidence", 0))
  601. if "transcript" not in best_hypothesis: raise UnknownValueError()
  602. return best_hypothesis["transcript"]
  603. def recognize_google_cloud(self, audio_data, language="en-US", preferred_phrases=None, show_all=False):
  604. """
  605. Performs speech recognition on ``audio_data`` (an ``AudioData`` instance), using the Google Cloud Speech API.
  606. This requires a Google Cloud Platform account; see the `Google Cloud Speech API Quickstart <https://cloud.google.com/speech/docs/getting-started>`__ for details and instructions.
  607. The recognition language is determined by ``language``, which is a BCP-47 language tag like ``"en-US"`` (US English). For more information see the `RecognitionConfig documentation <https://cloud.google.com/speech/reference/rest/v1beta1/RecognitionConfig>`__.
  608. If ``preferred_phrases`` is a list of phrase strings, those given phrases will be more likely to be recognized over similar-sounding alternatives. This is useful for things like keyword/command recognition or adding new phrases that aren't in Google's vocabulary. Note that the API imposes certain `restrictions on the list of phrase strings <https://cloud.google.com/speech/limits#content>`__.
  609. Returns the most likely transcription if ``show_all`` is False (the default). Otherwise, returns the raw API response as a JSON dictionary.
  610. Raises a ``speech_recognition.UnknownValueError`` exception if the speech is unintelligible. Raises a ``speech_recognition.RequestError`` exception if the speech recognition operation failed, if the credentials aren't valid, or if there is no Internet connection.
  611. """
  612. assert isinstance(audio_data, AudioData), "`audio_data` must be audio data"
  613. assert isinstance(language, str), "`language` must be a string"
  614. assert preferred_phrases is None or all(isinstance(preferred_phrases, basestring) for preferred_phrases in preferred_phrases), "`preferred_phrases` must be a list of strings"
  615. # See https://cloud.google.com/speech/reference/rest/v1beta1/RecognitionConfig
  616. flac_data = audio_data.get_flac_data(
  617. convert_rate=None if 8000 <= audio_data.sample_rate <= 48000 else max(8000, min(audio_data.sample_rate, 48000)), # audio sample rate must be between 8 kHz and 48 kHz inclusive - clamp sample rate into this range
  618. convert_width=2 # audio samples must be 16-bit
  619. )
  620. speech_service = self.get_speech_service()
  621. if preferred_phrases is None:
  622. speech_config = {"encoding": "FLAC", "sampleRate": audio_data.sample_rate, "languageCode": language}
  623. else:
  624. speech_config = {"encoding": "FLAC", "sampleRate": audio_data.sample_rate, "languageCode": language, "speechContext": {"phrases": preferred_phrases}}
  625. request = speech_service.speech().syncrecognize(body={"audio": {"content": base64.b64encode(flac_data).decode("utf8")}, "config": speech_config})
  626. import googleapiclient.errors
  627. try:
  628. response = request.execute()
  629. except googleapiclient.errors.HttpError as e:
  630. raise RequestError(e)
  631. except URLError as e:
  632. raise RequestError("recognition connection failed: {0}".format(e.reason))
  633. if show_all: return response
  634. if "results" not in response or len(response["results"]) == 0: raise UnknownValueError()
  635. transcript = ""
  636. for result in response["results"]:
  637. transcript += result["alternatives"][0]["transcript"].strip() + " "
  638. return transcript.strip()
  639. @staticmethod
  640. def get_speech_service():
  641. global CACHED_GOOGLE_CLOUD_SPEECH_SERVICES
  642. if CACHED_GOOGLE_CLOUD_SPEECH_SERVICES is not None:
  643. return CACHED_GOOGLE_CLOUD_SPEECH_SERVICES
  644. try:
  645. from oauth2client.client import GoogleCredentials
  646. from googleapiclient.discovery import build
  647. credentials = GoogleCredentials.get_application_default()
  648. service = build("speech", "v1beta1", credentials=credentials)
  649. CACHED_GOOGLE_CLOUD_SPEECH_SERVICES = service
  650. return service
  651. except ImportError:
  652. raise ImportError("Could not find google-api-python-client; check "
  653. "installation")
  654. def recognize_wit(self, audio_data, key, show_all=False):
  655. """
  656. Performs speech recognition on ``audio_data`` (an ``AudioData`` instance), using the Wit.ai API.
  657. The Wit.ai API key is specified by ``key``. Unfortunately, these are not available without `signing up for an account <https://wit.ai/>`__ and creating an app. You will need to add at least one intent to the app before you can see the API key, though the actual intent settings don't matter.
  658. To get the API key for a Wit.ai app, go to the app's overview page, go to the section titled "Make an API request", and look for something along the lines of ``Authorization: Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX``; ``XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`` is the API key. Wit.ai API keys are 32-character uppercase alphanumeric strings.
  659. The recognition language is configured in the Wit.ai app settings.
  660. Returns the most likely transcription if ``show_all`` is false (the default). Otherwise, returns the `raw API response <https://wit.ai/docs/http/20141022#get-intent-via-text-link>`__ as a JSON dictionary.
  661. Raises a ``speech_recognition.UnknownValueError`` exception if the speech is unintelligible. Raises a ``speech_recognition.RequestError`` exception if the speech recognition operation failed, if the key isn't valid, or if there is no internet connection.
  662. """
  663. assert isinstance(audio_data, AudioData), "Data must be audio data"
  664. assert isinstance(key, str), "``key`` must be a string"
  665. wav_data = audio_data.get_wav_data(
  666. convert_rate=None if audio_data.sample_rate >= 8000 else 8000, # audio samples must be at least 8 kHz
  667. convert_width=2 # audio samples should be 16-bit
  668. )
  669. url = "https://api.wit.ai/speech?v=20160526"
  670. request = Request(url, data=wav_data, headers={"Authorization": "Bearer {}".format(key), "Content-Type": "audio/wav"})
  671. try:
  672. response = urlopen(request, timeout=self.operation_timeout)
  673. except HTTPError as e:
  674. raise RequestError("recognition request failed: {}".format(e.reason))
  675. except URLError as e:
  676. raise RequestError("recognition connection failed: {}".format(e.reason))
  677. response_text = response.read().decode("utf-8")
  678. result = json.loads(response_text)
  679. # return results
  680. if show_all: return result
  681. if "_text" not in result or result["_text"] is None: raise UnknownValueError()
  682. return result["_text"]
  683. def recognize_bing(self, audio_data, key, language="en-US", show_all=False):
  684. """
  685. Performs speech recognition on ``audio_data`` (an ``AudioData`` instance), using the Microsoft Bing Voice Recognition API.
  686. The Microsoft Bing Voice Recognition API key is specified by ``key``. Unfortunately, these are not available without `signing up for an account <https://www.microsoft.com/cognitive-services/en-us/speech-api>`__ with Microsoft Cognitive Services.
  687. To get the API key, go to the `Microsoft Cognitive Services subscriptions overview <https://www.microsoft.com/cognitive-services/en-us/subscriptions>`__, go to the entry titled "Speech", and look for the key under the "Keys" column. Microsoft Bing Voice Recognition API keys are 32-character lowercase hexadecimal strings.
  688. The recognition language is determined by ``language``, an RFC5646 language tag like ``"en-US"`` (US English) or ``"fr-FR"`` (International French), defaulting to US English. A list of supported language values can be found in the `API documentation <https://www.microsoft.com/cognitive-services/en-us/speech-api/documentation/api-reference-rest/BingVoiceRecognition#user-content-4-supported-locales>`__.
  689. Returns the most likely transcription if ``show_all`` is false (the default). Otherwise, returns the `raw API response <https://www.microsoft.com/cognitive-services/en-us/speech-api/documentation/api-reference-rest/BingVoiceRecognition#user-content-3-voice-recognition-responses>`__ as a JSON dictionary.
  690. Raises a ``speech_recognition.UnknownValueError`` exception if the speech is unintelligible. Raises a ``speech_recognition.RequestError`` exception if the speech recognition operation failed, if the key isn't valid, or if there is no internet connection.
  691. """
  692. assert isinstance(audio_data, AudioData), "Data must be audio data"
  693. assert isinstance(key, str), "``key`` must be a string"
  694. assert isinstance(language, str), "``language`` must be a string"
  695. access_token, expire_time = getattr(self, "bing_cached_access_token", None), getattr(self, "bing_cached_access_token_expiry", None)
  696. allow_caching = True
  697. try:
  698. from time import monotonic # we need monotonic time to avoid being affected by system clock changes, but this is only available in Python 3.3+
  699. except ImportError:
  700. try:
  701. from monotonic import monotonic # use time.monotonic backport for Python 2 if available (from https://pypi.python.org/pypi/monotonic)
  702. except (ImportError, RuntimeError):
  703. expire_time = None # monotonic time not available, don't cache access tokens
  704. allow_caching = False # don't allow caching, since monotonic time isn't available
  705. if expire_time is None or monotonic() > expire_time: # caching not enabled, first credential request, or the access token from the previous one expired
  706. # get an access token using OAuth
  707. credential_url = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken"
  708. credential_request = Request(credential_url, data=b"", headers={
  709. "Content-type": "application/x-www-form-urlencoded",
  710. "Content-Length": "0",
  711. "Ocp-Apim-Subscription-Key": key,
  712. })
  713. if allow_caching:
  714. start_time = monotonic()
  715. try:
  716. credential_response = urlopen(credential_request, timeout=self.operation_timeout)
  717. except HTTPError as e:
  718. raise RequestError("recognition request failed: {}".format(e.reason))
  719. except URLError as e:
  720. raise RequestError("recognition connection failed: {}".format(e.reason))
  721. access_token = credential_response.read().decode("utf-8")
  722. if allow_caching:
  723. # save the token for the duration it is valid for
  724. self.bing_cached_access_token = access_token
  725. self.bing_cached_access_token_expiry = start_time + 600 # according to https://www.microsoft.com/cognitive-services/en-us/Speech-api/documentation/API-Reference-REST/BingVoiceRecognition, the token expires in exactly 10 minutes
  726. wav_data = audio_data.get_wav_data(
  727. convert_rate=16000, # audio samples must be 8kHz or 16 kHz
  728. convert_width=2 # audio samples should be 16-bit
  729. )
  730. url = "https://speech.platform.bing.com/recognize/query?{}".format(urlencode({
  731. "version": "3.0",
  732. "requestid": uuid.uuid4(),
  733. "appID": "D4D52672-91D7-4C74-8AD8-42B1D98141A5",
  734. "format": "json",
  735. "locale": language,
  736. "device.os": "wp7",
  737. "scenarios": "ulm",
  738. "instanceid": uuid.uuid4(),
  739. "result.profanitymarkup": "0",
  740. }))
  741. request = Request(url, data=wav_data, headers={
  742. "Authorization": "Bearer {}".format(access_token),
  743. "Content-Type": "audio/wav; samplerate=16000; sourcerate={}; trustsourcerate=true".format(audio_data.sample_rate),
  744. })
  745. try:
  746. response = urlopen(request, timeout=self.operation_timeout)
  747. except HTTPError as e:
  748. raise RequestError("recognition request failed: {}".format(e.reason))
  749. except URLError as e:
  750. raise RequestError("recognition connection failed: {}".format(e.reason))
  751. response_text = response.read().decode("utf-8")
  752. result = json.loads(response_text)
  753. # return results
  754. if show_all: return result
  755. if "header" not in result or "lexical" not in result["header"]: raise UnknownValueError()
  756. return result["header"]["lexical"]
  757. def recognize_houndify(self, audio_data, client_id, client_key, show_all=False):
  758. """
  759. Performs speech recognition on ``audio_data`` (an ``AudioData`` instance), using the Houndify API.
  760. The Houndify client ID and client key are specified by ``client_id`` and ``client_key``, respectively. Unfortunately, these are not available without `signing up for an account <https://www.houndify.com/signup>`__. Once logged into the `dashboard <https://www.houndify.com/dashboard>`__, you will want to select "Register a new client", and fill in the form as necessary. When at the "Enable Domains" page, enable the "Speech To Text Only" domain, and then select "Save & Continue".
  761. To get the client ID and client key for a Houndify client, go to the `dashboard <https://www.houndify.com/dashboard>`__ and select the client's "View Details" link. On the resulting page, the client ID and client key will be visible. Client IDs and client keys are both Base64-encoded strings.
  762. Currently, only English is supported as a recognition language.
  763. Returns the most likely transcription if ``show_all`` is false (the default). Otherwise, returns a JSON dictionary.
  764. Raises a ``speech_recognition.UnknownValueError`` exception if the speech is unintelligible. Raises a ``speech_recognition.RequestError`` exception if the speech recognition operation failed, if the key isn't valid, or if there is no internet connection.
  765. """
  766. assert isinstance(audio_data, AudioData), "Data must be audio data"
  767. assert isinstance(client_id, str), "``client_id`` must be a string"
  768. assert isinstance(client_key, str), "``client_key`` must be a string"
  769. wav_data = audio_data.get_wav_data(
  770. convert_rate=None if audio_data.sample_rate in [8000, 16000] else 16000, # audio samples must be 8 kHz or 16 kHz
  771. convert_width=2 # audio samples should be 16-bit
  772. )
  773. url = "https://api.houndify.com/v1/audio"
  774. user_id, request_id = str(uuid.uuid4()), str(uuid.uuid4())
  775. request_time = str(int(time.time()))
  776. request_signature = base64.urlsafe_b64encode(
  777. hmac.new(
  778. base64.urlsafe_b64decode(client_key),
  779. user_id.encode("utf-8") + b";" + request_id.encode("utf-8") + request_time.encode("utf-8"),
  780. hashlib.sha256
  781. ).digest() # get the HMAC digest as bytes
  782. ).decode("utf-8")
  783. request = Request(url, data=wav_data, headers={
  784. "Content-Type": "application/json",
  785. "Hound-Request-Info": json.dumps({"ClientID": client_id, "UserID": user_id}),
  786. "Hound-Request-Authentication": "{};{}".format(user_id, request_id),
  787. "Hound-Client-Authentication": "{};{};{}".format(client_id, request_time, request_signature)
  788. })
  789. try:
  790. response = urlopen(request, timeout=self.operation_timeout)
  791. except HTTPError as e:
  792. raise RequestError("recognition request failed: {}".format(e.reason))
  793. except URLError as e:
  794. raise RequestError("recognition connection failed: {}".format(e.reason))
  795. response_text = response.read().decode("utf-8")
  796. result = json.loads(response_text)
  797. # return results
  798. if show_all: return result
  799. if "Disambiguation" not in result or result["Disambiguation"] is None:
  800. raise UnknownValueError()
  801. return result['Disambiguation']['ChoiceData'][0]['Transcription']
  802. def recognize_ibm(self, audio_data, username, password, language="en-US", show_all=False):
  803. """
  804. Performs speech recognition on ``audio_data`` (an ``AudioData`` instance), using the IBM Speech to Text API.
  805. The IBM Speech to Text username and password are specified by ``username`` and ``password``, respectively. Unfortunately, these are not available without `signing up for an account <https://console.ng.bluemix.net/registration/>`__. Once logged into the Bluemix console, follow the instructions for `creating an IBM Watson service instance <https://www.ibm.com/watson/developercloud/doc/getting_started/gs-credentials.shtml>`__, where the Watson service is "Speech To Text". IBM Speech to Text usernames are strings of the form XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX, while passwords are mixed-case alphanumeric strings.
  806. The recognition language is determined by ``language``, an RFC5646 language tag with a dialect like ``"en-US"`` (US English) or ``"zh-CN"`` (Mandarin Chinese), defaulting to US English. The supported language values are listed under the ``model`` parameter of the `audio recognition API documentation <https://www.ibm.com/watson/developercloud/speech-to-text/api/v1/#sessionless_methods>`__, in the form ``LANGUAGE_BroadbandModel``, where ``LANGUAGE`` is the language value.
  807. Returns the most likely transcription if ``show_all`` is false (the default). Otherwise, returns the `raw API response <https://www.ibm.com/watson/developercloud/speech-to-text/api/v1/#sessionless_methods>`__ as a JSON dictionary.
  808. Raises a ``speech_recognition.UnknownValueError`` exception if the speech is unintelligible. Raises a ``speech_recognition.RequestError`` exception if the speech recognition operation failed, if the key isn't valid, or if there is no internet connection.
  809. """
  810. assert isinstance(audio_data, AudioData), "Data must be audio data"
  811. assert isinstance(username, str), "``username`` must be a string"
  812. assert isinstance(password, str), "``password`` must be a string"
  813. flac_data = audio_data.get_flac_data(
  814. convert_rate=None if audio_data.sample_rate >= 16000 else 16000, # audio samples should be at least 16 kHz
  815. convert_width=None if audio_data.sample_width >= 2 else 2 # audio samples should be at least 16-bit
  816. )
  817. url = "https://stream.watsonplatform.net/speech-to-text/api/v1/recognize?{}".format(urlencode({
  818. "profanity_filter": "false",
  819. "continuous": "true",
  820. "model": "{}_BroadbandModel".format(language),
  821. }))
  822. request = Request(url, data=flac_data, headers={
  823. "Content-Type": "audio/x-flac",
  824. "X-Watson-Learning-Opt-Out": "true", # prevent requests from being logged, for improved privacy
  825. })
  826. authorization_value = base64.standard_b64encode("{}:{}".format(username, password).encode("utf-8")).decode("utf-8")
  827. request.add_header("Authorization", "Basic {}".format(authorization_value))
  828. try:
  829. response = urlopen(request, timeout=self.operation_timeout)
  830. except HTTPError as e:
  831. raise RequestError("recognition request failed: {}".format(e.reason))
  832. except URLError as e:
  833. raise RequestError("recognition connection failed: {}".format(e.reason))
  834. response_text = response.read().decode("utf-8")
  835. result = json.loads(response_text)
  836. # return results
  837. if show_all: return result
  838. if "results" not in result or len(result["results"]) < 1 or "alternatives" not in result["results"][0]:
  839. raise UnknownValueError()
  840. transcription = []
  841. for utterance in result["results"]:
  842. if "alternatives" not in utterance: raise UnknownValueError()
  843. for hypothesis in utterance["alternatives"]:
  844. if "transcript" in hypothesis:
  845. transcription.append(hypothesis["transcript"])
  846. return "\n".join(transcription)
  847. def get_flac_converter():
  848. """Returns the absolute path of a FLAC converter executable, or raises an OSError if none can be found."""
  849. flac_converter = shutil_which("flac") # check for installed version first
  850. if flac_converter is None: # flac utility is not installed
  851. base_path = os.path.dirname(os.path.abspath(__file__)) # directory of the current module file, where all the FLAC bundled binaries are stored
  852. system, machine = platform.system(), platform.machine()
  853. if system == "Windows" and machine in {"i686", "i786", "x86", "x86_64", "AMD64"}:
  854. flac_converter = os.path.join(base_path, "flac-win32.exe")
  855. elif system == "Darwin" and machine in {"i686", "i786", "x86", "x86_64", "AMD64"}:
  856. flac_converter = os.path.join(base_path, "flac-mac.exe")
  857. elif system == "Linux" and machine in {"i686", "i786", "x86"}:
  858. flac_converter = os.path.join(base_path, "flac-linux-x86")
  859. elif system == "Linux" and machine in {"x86_64", "AMD64"}:
  860. flac_converter = os.path.join(base_path, "flac-linux-x86_64")
  861. else: # no FLAC converter available
  862. raise OSError("FLAC conversion utility not available - consider installing the FLAC command line application by running `apt-get install flac` or your operating system's equivalent")
  863. # mark FLAC converter as executable if possible
  864. try:
  865. stat_info = os.stat(flac_converter)
  866. os.chmod(flac_converter, stat_info.st_mode | stat.S_IEXEC)
  867. except OSError: pass
  868. return flac_converter
  869. def shutil_which(pgm):
  870. """Python 2 compatibility: backport of ``shutil.which()`` from Python 3"""
  871. path = os.getenv('PATH')
  872. for p in path.split(os.path.pathsep):
  873. p = os.path.join(p, pgm)
  874. if os.path.exists(p) and os.access(p, os.X_OK):
  875. return p
  876. class tempfile_TemporaryDirectory(object):
  877. """Python 2 compatibility: backport of ``tempfile.TemporaryDirectory`` from Python 3"""
  878. def __enter__(self):
  879. self.name = tempfile.mkdtemp()
  880. return self.name
  881. def __exit__(self, exc_type, exc_value, traceback):
  882. shutil.rmtree(self.name)
  883. # ===============================
  884. # backwards compatibility shims
  885. # ===============================
  886. WavFile = AudioFile # WavFile was renamed to AudioFile in 3.4.1
  887. def recognize_api(self, audio_data, client_access_token, language="en", session_id=None, show_all=False):
  888. wav_data = audio_data.get_wav_data(convert_rate=16000, convert_width=2)
  889. url = "https://api.api.ai/v1/query"
  890. while True:
  891. boundary = uuid.uuid4().hex
  892. if boundary.encode("utf-8") not in wav_data: break
  893. if session_id is None: session_id = uuid.uuid4().hex
  894. data = b"--" + boundary.encode("utf-8") + b"\r\n" + b"Content-Disposition: form-data; name=\"request\"\r\n" + b"Content-Type: application/json\r\n" + b"\r\n" + b"{\"v\": \"20150910\", \"sessionId\": \"" + session_id.encode("utf-8") + b"\", \"lang\": \"" + language.encode("utf-8") + b"\"}\r\n" + b"--" + boundary.encode("utf-8") + b"\r\n" + b"Content-Disposition: form-data; name=\"voiceData\"; filename=\"audio.wav\"\r\n" + b"Content-Type: audio/wav\r\n" + b"\r\n" + wav_data + b"\r\n" + b"--" + boundary.encode("utf-8") + b"--\r\n"
  895. request = Request(url, data=data, headers={"Authorization": "Bearer {}".format(client_access_token), "Content-Length": str(len(data)), "Expect": "100-continue", "Content-Type": "multipart/form-data; boundary={}".format(boundary)})
  896. try: response = urlopen(request, timeout=10)
  897. except HTTPError as e: raise RequestError("recognition request failed: {}".format(e.reason))
  898. except URLError as e: raise RequestError("recognition connection failed: {}".format(e.reason))
  899. response_text = response.read().decode("utf-8")
  900. result = json.loads(response_text)
  901. if show_all: return result
  902. if "status" not in result or "errorType" not in result["status"] or result["status"]["errorType"] != "success":
  903. raise UnknownValueError()
  904. return result["result"]["resolvedQuery"]
  905. Recognizer.recognize_api = classmethod(recognize_api) # API.AI Speech Recognition is deprecated/not recommended as of 3.5.0, and currently is only optionally available for paid plans