
    ,h`C                       d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlZddlZddlZddlZddlZddlZdZdZdZ	 ddlmZ ddlmZmZmZmZ  G d
 de!      Z" G d de!      Z# G d de!      Z$ G d de%      Z& G d de&      Z' G d de&      Z( G d de%      Z) G d de&      Z*d Z+d Z, G d de%      Z-e(Z.ddZ/ e0e/      e*_/        y# e$ r ddlmZ ddlmZmZ dd	l mZmZ Y w xY w) ziLibrary for performing speech recognition, with support for several engines and APIs, online and offline.    NzAnthony Zhang (Uberi)z3.8.1BSD)	urlencode)RequesturlopenURLError	HTTPError)r   r   )r   r   c                       e Zd Zy)WaitTimeoutErrorN__name__
__module____qualname__     ]/var/www/html/Resume-Scraper/venv/lib/python3.12/site-packages/speech_recognition/__init__.pyr
   r
   %       r   r
   c                       e Zd Zy)RequestErrorNr   r   r   r   r   r   (   r   r   r   c                       e Zd Zy)UnknownValueErrorNr   r   r   r   r   r   +   r   r   r   c                       e Zd Zd Zd Zd Zy)AudioSourcec                     t        d      Nzthis is an abstract classNotImplementedErrorselfs    r   __init__zAudioSource.__init__/       !"=>>r   c                     t        d      r   r   r   s    r   	__enter__zAudioSource.__enter__2   r    r   c                     t        d      r   r   r   exc_type	exc_value	tracebacks       r   __exit__zAudioSource.__exit__5   r    r   N)r   r   r   r   r"   r(   r   r   r   r   r   .   s    ???r   r   c                   Z    e Zd ZdZd
dZed        Zed        Zd Zd Z	 G d d	e
      Zy)
Microphoneaz  
    Creates a new ``Microphone`` instance, which represents a physical microphone on the computer. Subclass of ``AudioSource``.

    This will throw an ``AttributeError`` if you don't have PyAudio 0.2.11 or later installed.

    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.

    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.

    The microphone audio is recorded in chunks of ``chunk_size`` samples, at a rate of ``sample_rate`` samples per second (Hertz). If not specified, the value of ``sample_rate`` is determined automatically from the system's microphone settings.

    Higher ``sample_rate`` values result in better audio quality, but also more bandwidth (and therefore, slower recognition). Additionally, some CPUs, such as those in older Raspberry Pi models, can't keep up if this value is too high.

    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.
    Nc                 t   |t        |t              sJ d       |t        |t              r|dkD  sJ d       t        |t              r|dkD  sJ d       | j                         | _        | j                  j	                         }	 |j                         }|'d|cxk  r|k  sn J dj                  ||dz
               |t||j                  |      n|j                         }t        |j                  d      t        t        f      r|d   dkD  sJ dj                  |             t        |d         }|| _        | j                  j                  | _        | j                  j                  | j                        | _        || _        || _        d | _        d | _        y # t        $ r |j                           w xY w)	Nz'Device index must be None or an integerr   z.Sample rate must be None or a positive integerz%Chunk size must be a positive integerzcDevice index out of range ({} devices available; device index should be between 0 and {} inclusive)   defaultSampleRatez-Invalid device info returned from PyAudio: {})
isinstanceintget_pyaudiopyaudio_modulePyAudioget_device_countformatget_device_info_by_indexget_default_input_device_infogetfloat	Exception	terminatedevice_indexpaInt16get_sample_sizeSAMPLE_WIDTHSAMPLE_RATECHUNKaudiostream)r   r;   sample_rate
chunk_sizerA   countdevice_infos          r   r   zMicrophone.__init__I   s   #z,'DoFoo"z+s'CVW  	K  [K  	K*c*zA~f?ff #..0##++-
	**,E'L050  q  3X  3_  3_  `e  gl  op  gp  3q  q"NZNfe<<\Jlq  mP  mP  mR!+//2E"FPSUZefyZz}~Z~  D  Ap  Aw  Aw  xC  AD  D!+.A"BC
 )))11 //??L&

  	OO	s   B/F F7c                      	 ddl } ddlm}  || j
                         |d      k  r$t        dj                  | j
                              | S # t        $ r t        d      w xY w)z
        Imports the pyaudio module and checks its version. Throws exceptions if pyaudio can't be found or a wrong version is installed
        r   Nz*Could not find PyAudio; check installation)LooseVersionz0.2.11z6PyAudio 0.2.11 or later is required (found version {}))pyaudioImportErrorAttributeErrordistutils.versionrH   __version__r4   )rI   rH   s     r   r0   zMicrophone.get_pyaudiof   sj    
	O 	3++,|H/EE !Y!`!`ahatat!uvv  	O !MNN	Os   A A"c                  :   t         j                         j                         } 	 g }t        | j	                               D ]3  }| j                  |      }|j                  |j                  d             5 	 | j                          |S # | j                          w xY w)a_  
        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.

        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``.
        name)	r*   r0   r2   ranger3   r5   appendr7   r:   )rA   resultirF   s       r   list_microphone_namesz Microphone.list_microphone_namest   s     &&(002	F51134 7#<<Q?koof567 OO OOs   AB Bc           
      ~   | j                   J d       | j                  j                         | _        	 t        j                  | j                  j                  | j                  d| j                  | j                  | j                  d            | _         | S # t        $ r | j                  j                           w xY w)N5This audio source is already inside a context managerr,   T)input_device_indexchannelsr4   rateframes_per_bufferinput)rB   r1   r2   rA   r*   MicrophoneStreamopenr;   r4   r?   r@   r9   r:   r   s    r   r"   zMicrophone.__enter__   s    {{"[$[[((002

	$55

'+'8'81;;T-=-=QUQ[Q[   DK   	JJ  "	s   A!B %B<c                     	 | j                   j                          d | _         | j                  j                          y # d | _         | j                  j                          w xY wN)rB   closerA   r:   r$   s       r   r(   zMicrophone.__exit__   sI    	#KKDKJJ  " DKJJ  "s	   > #A!c                       e Zd Zd Zd Zd Zy)Microphone.MicrophoneStreamc                     || _         y r_   )pyaudio_stream)r   rd   s     r   r   z$Microphone.MicrophoneStream.__init__   s
    "0Dr   c                 <    | j                   j                  |d      S )NF)exception_on_overflow)rd   read)r   sizes     r   rg   z Microphone.MicrophoneStream.read   s    &&++D+NNr   c                     	 | j                   j                         s| j                   j                          | j                   j                          y # | j                   j                          w xY wr_   )rd   
is_stoppedstop_streamr`   r   s    r   r`   z!Microphone.MicrophoneStream.close   sP    ,**557''335##))+##))+s   4A A-N)r   r   r   r   rg   r`   r   r   r   r\   rb      s    	1	O	,r   r\   )NNi   )r   r   r   __doc__r   staticmethodr0   rT   r"   r(   objectr\   r   r   r   r*   r*   9   sJ    :      #,6 ,r   r*   c                   8    e Zd ZdZd Zd Zd Z G d de      Zy)	AudioFilea{  
    Creates a new ``AudioFile`` instance given a WAV/AIFF/FLAC audio file ``filename_or_fileobject``. Subclass of ``AudioSource``.

    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.

    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.

    WAV files must be in PCM/LPCM format; WAVE_FORMAT_EXTENSIBLE and compressed WAV are not supported and may result in undefined behaviour.

    Both AIFF and AIFF-C (compressed AIFF) formats are supported.

    FLAC files must be in native FLAC format; OGG-FLAC is not supported and may result in undefined behaviour.
    c                     t        |t        d      t        d      f      st        |d      sJ d       || _        d | _        d | _        d | _        d| _        d | _        d | _	        d | _
        y )N rg   z@Given audio file must be a filename string or a file-like objectF)r.   typehasattrfilename_or_fileobjectrB   DURATIONaudio_readerlittle_endianr?   r@   FRAME_COUNT)r   ru   s     r   r   zAudioFile.__init__   su    048T#Y2GHGTjlrLs  	x  vx  	x&<# "
r   c           
         | j                   J d       	 t        j                  | j                  d      | _        d| _        d| j                  j5                         cxk  rdk  sJ d        J d       | j                  j7                         | _        d}	| j8                  dk(  r!t;        j<                  d| j8                  d       | j                  jA                         | _!        d| _"        | j                  jG                         | _$        | jH                  tK        | jB                        z  | _&        tN        jQ                  | j                  | j
                  |	      | _         | S # t        j                  t        f$ r 	 t        j                  | j                  d      | _        d| _        n# t        j                  t        f$ r t        | j                  d      r| j                  j                         }n<t        | j                  d      5 }|j                         }d d d        n# 1 sw Y   nxY wt               }t        j                  dk(  rMt        j                         }|xj                   t        j"                  z  c_        t        j$                  |_        nd }t        j(                  |ddd	d
dgt        j*                  t        j*                  |      }|j-                        \  }}t/        j0                  |      }	 t        j                  |d      | _        n(# t        j                  t        f$ r t3        d      w xY wd| _        Y nw xY wY w xY w# t:        j>                  $ r d}	d| _        Y w xY w)NrV   rbTFrg   nt--stdout--totally-silentz--decodez--force-aiff-format-stdinstdoutstartupinfozuAudio file could not be read as PCM WAV, AIFF/AIFF-C, or Native FLAC; check if file is corrupted or in another formatr,      zAudio must be mono or stereo   r   r      i   ))rB   waver]   ru   rw   rx   ErrorEOFErroraifcrt   rg   get_flac_converterosrO   
subprocessSTARTUPINFOdwFlagsSTARTF_USESHOWWINDOWSW_HIDEwShowWindowPopenPIPEcommunicateioBytesIO
ValueErrorgetnchannelsgetsampwidthr>   audioopbiaserrorgetframerater?   r@   
getnframesry   r8   rv   rp   AudioFileStream)
r   	flac_datafflac_converterstartup_infoprocess	aiff_data_	aiff_file&samples_24_bit_pretending_to_be_32_bits
             r   r"   zAudioFile.__enter__   s   {{"[$[[$	+ $		$*E*Et LD!%DD D%%22499Y;YY9Y;YY --::< 27.!c4#4#4a8
  ,,99;
,,779((51A1A+BB//0A0A4CUCUW}~c 

H%  	++$(IId.I.I4$P!%*"JJ) +466? $ ; ; @ @ BId994@[ASTSYSYS[y[[[ "4!577d?#-#9#9#;L ((J,K,KK(/9/A/AL,#'L$**" 2 5	,
 $l\  '229=	1JJy1	^(,		)T(BD%

H- ^$  &]  ^  ^^%*"7+ 	+P == &9=6$%!&sy   ,E" #!M "M=,F+)M+A!MH&	M&H/+CMLM%M
MMMMMM;:M;c                     t        | j                  d      s| j                  j                          d | _        d | _        y )Nrg   )rt   ru   rw   r`   rB   rv   r$   s       r   r(   zAudioFile.__exit__   s2    t22F;##%r   c                       e Zd Zd ZddZy)AudioFile.AudioFileStreamc                 .    || _         || _        || _        y r_   )rw   rx   r   )r   rw   rx   r   s       r   r   z"AudioFile.AudioFileStream.__init__  s     ,D!.D:`D7r   c           
         | j                   j                  |dk(  r| j                   j                         n|      t        t              sd| j                   j                         | j                  set        t        d      rt        j                        n>dz
  d d   dj                  fdt        dz
  t                    D              z   | j                  r1dj                  fdt        dt                    D              d| j                   j                         dk7  rt        j                  dd      S )	Nr   byteswapr,   c              3   4   K   | ]  }|z   |d      ywr   Nr   .0rS   buffersample_widths     r   	<genexpr>z1AudioFile.AudioFileStream.read.<locals>.<genexpr>  s.       E`ghVAP\L\]^_aLaEb  E`   c              3   4   K   | ]  }d ||z    z     yw)    Nr   r   s     r   r   z1AudioFile.AudioFileStream.read.<locals>.<genexpr>  s"     !t1'F1Q5E,F"F!tr   r   r   )rw   
readframesr   r.   bytesr   rx   rt   r   r   joinrP   lenr   r   tomono)r   rh   r   r   s     @@r   rg   zAudioFile.AudioFileStream.read  sP   &&11TX\^T^$2C2C2N2N2PdhiFfe,sf,,99;L%%7J/$--flCF#L1$4$8b$89CHH  E`lqr~  BC  sC  EH  IO  EP  R^  m_  E`  =`  `F ::!tPUVWY\]cYdfrPs!tt   --/14 aCMr   N)r   )r   r   r   r   rg   r   r   r   r   r     s    	a
	r   r   N)	r   r   r   rl   r   r"   r(   rn   r   r   r   r   rp   rp      s#    
 7r& r   rp   c                   >    e Zd ZdZd Zd	dZd	dZd	dZd	dZd	dZ	y)
	AudioDataa  
    Creates a new ``AudioData`` instance, which represents mono audio data.

    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.

    The width of each sample, in bytes, is specified by ``sample_width``. Each group of ``sample_width`` bytes represents a single audio sample.

    The audio data is assumed to have a sample rate of ``sample_rate`` samples per second (Hertz).

    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.
    c                     |dkD  sJ d       |dz  dk(  rd|cxk  rdk  sJ d        J d       || _         || _        t        |      | _        y )Nr   z&Sample rate must be a positive integerr,   r   z.Sample width must be between 1 and 4 inclusive)
frame_datarC   r/   r   )r   r   rC   r   s       r   r   zAudioData.__init__,  s\    QH HHa1$l)?a)?qAqq)?qAqq$&-r   Nc                 x   ||dk\  sJ d       |||dn|k\  sJ d       |d}n(t        || j                  z  | j                  z  dz        }|t        | j                        }n(t        || j                  z  | j                  z  dz        }t        | j                  || | j                  | j                        S )ag  
        Returns a new ``AudioData`` instance, trimmed to a given time interval. In other words, an ``AudioData`` instance with the same audio data except starting at ``start_ms`` milliseconds in and ending ``end_ms`` milliseconds in.

        If not specified, ``start_ms`` defaults to the beginning of the audio, and ``end_ms`` defaults to the end.
        r   z*``start_ms`` must be a non-negative numberzI``end_ms`` must be a non-negative number greater or equal to ``start_ms``i  )r/   rC   r   r   r   r   )r   start_msend_ms
start_byteend_bytes        r   get_segmentzAudioData.get_segment3  s     8q=^2^^~1AAx!P  	^  S^  	^Jh)9)99D<M<MMRVVWJ>4??+HFT%5%558I8IIdRSHH=t?O?OQUQbQbccr   c           
      <   ||dkD  sJ d       |"|dz  dk(  rd|cxk  rdk  sJ d        J d       | j                   | j                  dk(  rt        j                  dd      |@| j                  |k7  r1t        j
                  | j                  d| j                  |d      \  }|| j                  |k7  r|dk(  rZt        j                  | j                  d      t        j                  d	dd       t        j                  | j                  |      n!t        j                  | j                  |      |dk(  rt        j                  dd      S # t        j                  $ r1 d	j                  fd
t        dt              d      D              Y aw xY w)a)  
        Returns a byte string representing the raw frame data for the audio represented by the ``AudioData`` instance.

        If ``convert_rate`` is specified and the audio sample rate is not ``convert_rate`` Hz, the resulting audio is resampled to match.

        If ``convert_width`` is specified and the audio samples are not ``convert_width`` bytes each, the resulting audio is converted to match.

        Writing these bytes directly to a file results in a valid `RAW/PCM audio file <https://en.wikipedia.org/wiki/Raw_audio_format>`__.
        Nr   z4Sample rate to convert to must be a positive integerr,   r   z<Sample width to convert to must be between 1 and 4 inclusiveir   r   c              3   4   K   | ]  }|d z   |dz      yw)r,   r   Nr   )r   rS   raw_datas     r   r   z)AudioData.get_raw_data.<locals>.<genexpr>b  s      'b!Qq1u(='br      )r   r   r   r   rC   ratecvlin2linr   r   rP   r   )r   convert_rateconvert_widthr   r   s       @r   get_raw_datazAudioData.get_raw_dataE  s    #|a'7o9oo$):a)?AD[Z[D[  	]  _]  	]D[  	]  _]  	]?? !||Ha6H #(8(8L(H!..43D3DaIYIY[gimnKHa $):):m)K!"??8T5F5FJ\\#q!,  'x9J9JMZH"??8T5F5FV A||Ha5H }} c"xx'buQPST\P]_`Ga'bbHcs   E AFFc                    | j                  ||      }|| j                  n|}|| j                  n|}t        j                         5 }t        j                  |d      }	 |j                  |       |j                  |       |j                  d       |j                  |       |j                         }|j                          	 ddd       |S # |j                          w xY w# 1 sw Y   S xY w)a!  
        Returns a byte string representing the contents of a WAV file containing the audio represented by the ``AudioData`` instance.

        If ``convert_width`` is specified and the audio samples are not ``convert_width`` bytes each, the resulting audio is converted to match.

        If ``convert_rate`` is specified and the audio sample rate is not ``convert_rate`` Hz, the resulting audio is resampled to match.

        Writing these bytes directly to a file results in a valid `WAV file <https://en.wikipedia.org/wiki/WAV>`__.
        Nwbr,   )r   rC   r   r   r   r   r]   setframeratesetsampwidthsetnchannelswriteframesgetvaluer`   )	r   r   r   r   rC   r   wav_file
wav_writerwav_datas	            r   get_wav_datazAudioData.get_wav_datan  s     $$\=A*6*>d&&L,9,At((} ZZ\ 		#X8T2J#''4''5''*&&x0#,,.  "		#    "		# s%   C#AC3C#C  C##C-c           
         | j                  ||      || j                  n|}|| j                  n|t        t        d      rt	        j
                        n>dz
  dd   dj                  fdt        dz
  t                    D              z   t        j                         5 }t        j                  |d      }	 |j                  |       |j                         |j                  d       |j!                         |j#                         }|j%                          	 ddd       |S # |j%                          w xY w# 1 sw Y   S xY w)aB  
        Returns a byte string representing the contents of an AIFF-C file containing the audio represented by the ``AudioData`` instance.

        If ``convert_width`` is specified and the audio samples are not ``convert_width`` bytes each, the resulting audio is converted to match.

        If ``convert_rate`` is specified and the audio sample rate is not ``convert_rate`` Hz, the resulting audio is resampled to match.

        Writing these bytes directly to a file results in a valid `AIFF-C file <https://en.wikipedia.org/wiki/Audio_Interchange_File_Format>`__.
        Nr   r,   r   r   c              3   4   K   | ]  }|z   |d      ywr   r   )r   rS   r   r   s     r   r   z*AudioData.get_aiff_data.<locals>.<genexpr>  s-       A`ef!lJZ[\]_J_A`  A`r   r   )r   rC   r   rt   r   r   r   rP   r   r   r   r   r]   r   r   r   r   r   r`   )	r   r   r   rC   r   aiff_writerr   r   r   s	          @@r   get_aiff_datazAudioData.get_aiff_data  sk    $$\=A*6*>d&&L,9,At((} 7J''',?Hq 0 4" 45  A`jop|  @A  qA  CF  GO  CP  R^  k_  A`  9`  `H ZZ\ 		$Y))It4K$((5((6((+''1%..0	!!#		$  !!#		$ s%   .E
AD5E
5EE

Ec                    |"|dz  dk(  rd|cxk  rdk  sJ d        J d       | j                   dkD  r|d}| j                  ||      }t               }t        j                  dk(  rMt        j                         }|xj                  t
        j                  z  c_        t
        j                  |_
        nd}t        j                  |ddd	d
gt
        j                  t
        j                  |      }|j                  |      \  }}|S )a  
        Returns a byte string representing the contents of a FLAC file containing the audio represented by the ``AudioData`` instance.

        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.

        If ``convert_rate`` is specified and the audio sample rate is not ``convert_rate`` Hz, the resulting audio is resampled to match.

        If ``convert_width`` is specified and the audio samples are not ``convert_width`` bytes each, the resulting audio is converted to match.

        Writing these bytes directly to a file results in a valid `FLAC file <https://en.wikipedia.org/wiki/FLAC>`__.
        Nr,   r   r   z<Sample width to convert to must be between 1 and 3 inclusiver|   r}   r~   z--bestr   r   )r   r   r   r   rO   r   r   r   r   r   r   r   r   r   )	r   r   r   r   r   r   r   r   stderrs	            r   get_flac_datazAudioData.get_flac_data  s    $):a)?AD[Z[D[  	]  _]  	]D[  	]  _]  	]q ]%:M $$\=A+-77d?%113L  J$C$CC '1'9'9L$L""*	$

 lT $//9	6r   NN)
r   r   r   rl   r   r   r   r   r   r   r   r   r   r   r      s(    
.d$'R6B!r   r   c                   r    e Zd Zd ZddZddZddZddZddZddZ	dd	Z
dd
ZddZddZddZddZy)
Recognizerc                 t    d| _         d| _        d| _        d| _        d| _        d| _        d| _        d| _        y)	z{
        Creates a new ``Recognizer`` instance, which represents a collection of speech recognition functionality.
        i,  Tg333333?g      ?g?Ng333333?g      ?)energy_thresholddynamic_energy_threshold!dynamic_energy_adjustment_dampingdynamic_energy_ratiopause_thresholdoperation_timeoutphrase_thresholdnon_speaking_durationr   s    r   r   zRecognizer.__init__  sD     !$(,%15.$'!"!% #%("r   Nc                    t        |t              sJ d       |j                  J d       t        j                         }|j
                  dz   |j                  z  }d}d}d}	 |r|s||z  }||kD  rd}|j                  j                  |j
                        }	t        |	      dk(  rn#|s|s||z  }|r||kD  rn|j                  |	       g|j                         }
|j                          t        |
|j                  |j                        S )a>  
        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.

        If ``duration`` is not specified, then it will record until there is no more audio input.
        Source must be an audio sourcezAudio source must be entered before recording, see documentation for ``AudioSource``; are you using ``source`` outside of a ``with`` statement?        r   FT)r.   r   rB   r   r   r@   r?   rg   r   writer   r`   r   r>   )r   sourcedurationoffsetframesseconds_per_bufferelapsed_timeoffset_timeoffset_reachedr   r   s              r   recordzRecognizer.record  s    &+.P0PP}}(  	|  +|  	|$llS0F4F4FFn11'%)N]]''5F6{aV 22x 7V$  __&
V%7%79L9LMMr   c                    t        |t              sJ d       |j                  J d       | j                  | j                  cxk\  rdk\  sJ  J |j
                  dz   |j                  z  }d}	 ||z  }||kD  ry|j                  j                  |j
                        }t        j                  ||j                        }| j                  |z  }|| j                  z  }| j                  |z  |d|z
  z  z   | _        )a-  
        Adjusts the energy threshold dynamically using audio from ``source`` (an ``AudioSource`` instance) to account for ambient noise.

        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.

        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.
        r   NzAudio source must be entered before adjusting, see documentation for ``AudioSource``; are you using ``source`` outside of a ``with`` statement?r   r   r,   )r.   r   rB   r   r   r@   r?   rg   r   rmsr>   r   r   r   )	r   r   r   r   r   r   energydampingtarget_energys	            r   adjust_for_ambient_noisez#Recognizer.adjust_for_ambient_noise  s    &+.P0PP}}(  	|  +|  	|##t'A'AFQFFFF$llS0F4F4FF ..Lh&]]''5F[[)<)<=F <<@RRG"T%>%>>M$($9$9G$CmWX[bWbFc$cD! r   c                    t         j                  j                  |       dd l}t         j                  j	                          |j                  t        j                  j                  |dd      j                         dj                  |      j                               }|j                  d       |j                  dj                  dgt        |      z        j                                |j                         }d}t        |j                        |j                  z  }	d }
t!        t#        j$                  d|	z              }t'        j(                  |	      }t'        j(                  |	      }	 ||	z  }|r||kD  rt+        d
      |j,                  j/                  |j                        }t        |      dk(  rn|j                  |       t1        j2                  ||j4                  d|j                  ||
      \  }}
|j                  |       |j7                  dj                  |            }|dk7  sJ d       |dkD  rndj                  |      |fS )Nr   	resourcesz
common.res,)resource_filename	model_strg      ?z0.4   )maxlenz8listening timed out while waiting for hotword to be saidr,   r   r   z0Error initializing streams or reading audio data)syspathrQ   snowboydetectpopSnowboyDetectr   r   encodeSetAudioGainSetSensitivityr   
SampleRater8   r@   r?   r/   mathceilcollectionsdequer
   rB   rg   r   r   r>   RunDetection)r   snowboy_locationsnowboy_hot_word_filesr   timeoutr  detectorsnowboy_sample_rater   r   resampling_statefive_seconds_buffer_countr   resampled_framesr   resampled_buffersnowboy_results                    r   snowboy_wait_for_hot_wordz$Recognizer.snowboy_wait_for_hot_word  s   () .. ggll+;[,W^^`hh56==? / 
 	c"%37M3N)N O V V XY&113"6<<063E3EE %(		!6H2H(I$J!""*CD&,,4MN..L<'1&'abb]]''5F6{aMM&! 29H[H[]^`f`r`r  uH  JZ  2[..##$45 &22388<L3MNN!R'[)[[!5! $ xx--r   c                    t        |t              sJ d       |j                  J d       | j                  | j                  cxk\  rdk\  sJ  J |wt
        j                  j                  t
        j                  j                  |d   d            sJ d       |d   D ](  }t
        j                  j                  |      r#J d        t        |j                        |j                  z  }t        t        j                  | j                  |z              }t        t        j                  | j                  |z              }t        t        j                  | j                  |z              }	d}
d}	 t!        j"                         }|	 |
|z  }
|r|
|kD  rt%        d	      |j                  j'                  |j                        }t)        |      dk(  rn|j+                  |       t)        |      |	kD  r|j-                          t/        j0                  ||j2                        }|| j4                  kD  rn| j6                  r;| j8                  |z  }|| j:                  z  }| j4                  |z  |d|z
  z  z   | _        |\  }}| j=                  ||||      \  }}|
|z  }
t)        |      dk(  rn|j+                  |       d
\  }}|
}	 |
|z  }
|r	|
|z
  |kD  rn|j                  j'                  |j                        }t)        |      dk(  rnT|j+                  |       |dz  }t/        j0                  ||j2                        }|| j4                  kD  rd}n|dz  }||kD  rn||z  }||k\  st)        |      dk(  rnt?        |	z
        D ]  }|jA                           dj                  |      }tC        ||j                  |j2                        S )a^  
        Records a single phrase from ``source`` (an ``AudioSource`` instance) into an ``AudioData`` instance, which it returns.

        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.

        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.

        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.

        The ``snowboy_configuration`` parameter allows integration with `Snowboy <https://snowboy.kitt.ai/>`__, an offline, high-accuracy, power-efficient hotword recognition engine. When used, this function will pause until Snowboy detects a hotword, after which it will unpause. This parameter should either be ``None`` to turn off Snowboy support, or a tuple of the form ``(SNOWBOY_LOCATION, LIST_OF_HOT_WORD_FILES)``, where ``SNOWBOY_LOCATION`` is the path to the Snowboy root directory, and ``LIST_OF_HOT_WORD_FILES`` is a list of paths to Snowboy hotword configuration files (`*.pmdl` or `*.umdl` format).

        This operation will always complete within ``timeout + phrase_timeout`` seconds if both are numbers, either by returning the audio data, or by raising a ``speech_recognition.WaitTimeoutError`` exception.
        r   zAudio source must be entered before listening, see documentation for ``AudioSource``; are you using ``source`` outside of a ``with`` statement?r   zsnowboydetect.pyz]``snowboy_configuration[0]`` must be a Snowboy root directory containing ``snowboydetect.py``r,   zS``snowboy_configuration[1]`` must be a list of Snowboy hot word configuration filesr   z5listening timed out while waiting for phrase to start)r   r   )"r.   r   rB   r   r   r   r  isfiler   r8   r@   r?   r/   r  r  r   r  r  r
   rg   r   rQ   popleftr   r   r>   r   r   r   r   r#  rP   r  r   )r   r   r  phrase_time_limitsnowboy_configurationhot_word_filer   pause_buffer_countphrase_buffer_countnon_speaking_buffer_countr   r   r   r   r  r  r  r  
delta_timepause_countphrase_countphrase_start_timerS   r   s                           r   listenzRecognizer.listenC  s    &+.P0PP}}(  	|  +|  	|##t'A'AFQFFFF ,77>>"'',,/DQ/GI["\]    `  !6q!9 Lww~~m4  L  7L  LL #6<<063E3EE 4+?+?BT+T!UV!$))D,A,ADV,V"WX$'		$2L2LOa2a(b$c!  &&(F$, $66L<'#9./fgg#]]//=F6{a'MM&)6{%>>( %[[1D1DEF 5 55u 44"&"H"HL^"^(.1J1J(J040E0E0OR_cdgncnRo0o-) . <Q8 "8%)%C%CDTVlntv}%~"

*v;!#Uf% )-%K , 22$8I)IL])]++FLL9v;!#Uf%! !VV-@-@AD111"#K1$K!33% * K'L22c&kQ6Fw | {%>>?MAMXXf%
V%7%79L9LMMr   c                      t        t              sJ d       dg fd}dfd	}t        j                  |      d_        j                          |S )as  
        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.

        Returns a function object that, when called, requests that the background listener thread stop. The background thread is a daemon and will not stop the program from exiting if there are no other non-daemon threads. The function accepts one parameter, ``wait_for_stop``: if truthy, the function will wait for the background listener to stop before returning, otherwise it will return immediately and the background listener thread might still be running for a second or two afterwards. Additionally, if you are using a truthy value for ``wait_for_stop``, you must call the function from the same thread you originally called ``listen_in_background`` from.

        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.

        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.
        r   Tc                      5 } d   r)	 j                  | d      }d   r
 |       	 d   r)d d d        y # t        $ r Y w xY w# 1 sw Y   y xY w)Nr   r,   )r1  r
   )srA   callbackr'  runningr   r   s     r   threaded_listenz8Recognizer.listen_in_background.<locals>.threaded_listen  sp     =1aj= $Aq2C D #1:xe'< aj= = , 	= =s+   A<A	AAAAAc                 6    dd<   | rj                          y y )NFr   )r   )wait_for_stoplistener_threadr6  s    r   stopperz0Recognizer.listen_in_background.<locals>.stopper  s     GAJ$$& r   )target)T)r.   r   	threadingThreaddaemonstart)r   r   r5  r'  r7  r;  r:  r6  s   ````  @@r   listen_in_backgroundzRecognizer.listen_in_background  sY     &+.P0PP&	= 	=	'
 $**/B!%r   c                    t        |t              sJ d       t        |t              s%t        |t              rt	        |      dk(  sJ d       |t        d |D              sJ d       	 ddlm}m}m} t        |d      rt        |j                  d      st        d      t        |t              rt        j                  j!                  t        j                  j#                  t        j                  j%                  t&                    d|      }	t        j                  j)                  |	      st        dj+                  |	            t        j                  j!                  |	d      }
t        j                  j!                  |	d      }t        j                  j!                  |	d      }n|\  }
}}t        j                  j)                  |
      st        dj+                  |
            t        j                  j-                  |      st        dj+                  |            t        j                  j-                  |      st        dj+                  |            |j                  j/                         }|j1                  d|
       |j1                  d|       |j1                  d|       |j1                  dt        j2                         |j                  |      }|j5                  dd      }|t7        d      5 }|j9                  d |D               |j;                          |j=                  d|j>                         |jA                  d       |jC                          |jE                  |d d!       |jG                          ddd       n|t        j                  jI                  |      st        d"j+                  |            t        j                  jK                  t        j                  j#                  |            }t        j                  jM                  t        j                  jO                  |            d   }d#j+                  ||      }t        j                  jI                  |      s[ ||      }|jQ                  d$j+                  |            }|jS                  ||jU                         d%      }|jW                  |       n |||jU                         d%      }|jY                  ||       |jA                  |       |jC                          |jE                  |d d!       |jG                          n3|jC                          |jE                  |d d!       |jG                          |r|S |j[                         }||j\                  S t_               # t        $ r t        d	      t        $ r t        d
      w xY w# 1 sw Y   `xY w)&al  
        Performs speech recognition on ``audio_data`` (an ``AudioData`` instance), using CMU Sphinx.

        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``. The ``language`` parameter can also be a tuple of filesystem paths, of the form ``(acoustic_parameters_directory, language_model_file, phoneme_dictionary_file)`` - this allows you to load arbitrary Sphinx models.

        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.

        Sphinx can also handle FSG or JSGF grammars. The parameter ``grammar`` expects a path to the grammar file. Note that if a JSGF grammar is passed, an FSG grammar will be created at the same location to speed up execution in the next run. If ``keyword_entries`` are passed, content of ``grammar`` will be ignored.

        Returns the most likely transcription if ``show_all`` is false (the default). Otherwise, returns the Sphinx ``pocketsphinx.pocketsphinx.Decoder`` object resulting from the recognition.

        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.
        !``audio_data`` must be audio datar   z``language`` must be a string or 3-tuple of Sphinx data file paths of the form ``(acoustic_parameters, language_model, phoneme_dictionary)``Nc              3      K   | ]9  \  }}t        |t        d       t        d       f      xr d|cxk  xr dk  nc  ; yw)rr   r   r,   Nr.   rs   r   keywordsensitivitys      r   r   z.Recognizer.recognize_sphinx.<locals>.<genexpr>  sO       .`  xLw~  ALj48TRUYBW.X.r]^bm]rqr]r.r  .`s   ?Az^``keyword_entries`` must be ``None`` or a list of pairs of strings and numbers between 0 and 1r   )pocketsphinxJsgfFsgModelzJmissing PocketSphinx module: ensure that PocketSphinx is set up correctly.zUbad PocketSphinx installation; try reinstalling PocketSphinx version 0.0.9 or better.Decoderdefault_configzYoutdated PocketSphinx installation; ensure you have PocketSphinx version 0.0.9 or better.zpocketsphinx-dataz2missing PocketSphinx language data directory: "{}"zacoustic-modelzlanguage-model.lm.binzpronounciation-dictionary.dictz>missing PocketSphinx language model parameters directory: "{}"z.missing PocketSphinx language model file: "{}"z2missing PocketSphinx phoneme dictionary file: "{}"z-hmmz-lmz-dictz-logfn>  r   r   r   wc              3   R   K   | ]  \  }}d j                  |d|z  dz
         ! yw)z
{} /1e{}/
d   n   N)r4   rF  s      r   r   z.Recognizer.recognize_sphinx.<locals>.<genexpr>  s4       AXlX_al]11'3;Ls;RS  As   %'keywordsFTzGrammar '{0}' does not exist.z{0}/{1}.fsgz{0}.{0}g      @)0r.   r   strtupler   allrI  rJ  rK  rJ   r   r   rt   rL  r   r  r   dirnamerealpath__file__isdirr4   r%  rM  
set_stringdevnullr   PortableNamedTemporaryFile
writelinesflushset_kwsrO   
set_search	start_uttprocess_rawend_uttexistsabspathsplitextbasenameget_rule	build_fsgget_logmath	writefileset_fsghyphypstrr   )r   
audio_datalanguagekeyword_entriesgrammarshow_allrI  rJ  rK  language_directoryacoustic_parameters_directorylanguage_model_filephoneme_dictionary_fileconfigdecoderr   r   grammar_pathgrammar_namefsg_pathjsgfrulefsg
hypothesiss                           r   recognize_sphinxzRecognizer.recognize_sphinx  s    *i0U2UU(C(Z%-HSQY]^_M_  	q  cq  	q&#  .`  P_  .`  +`  	B  bB  	B	xAA |Y/w|?S?SUe7fz{{h$!#bggoobgg>N>Nx>X.Y[npx!y77==!34"#Y#`#`as#tuu,.GGLL9KM],^)"$'',,/ACZ"[&(ggll3EGg&h#ZbW)+>@Www}}:;ahh  jG   H  I  Iww~~12QXXYlmnnww~~56U\\]tuvv %%446&"?@%!45'#:;(BJJ/&&v. **Q*O &+C0 
"A  Ap  A  A	 
AFF3"":.!!###HeT:!
" 
"  77>>'* !@!G!G!PQQ77??277??7+CDL77++BGG,<,<W,EFqIL$++L,GH77>>(+G}}}Y%5%5l%CDnnT7+>+>+@#Fh'x)<)<)>DOOL#.|,%6OO%6OOG^ [[]
!**;*;#;!!W  	mkll 	xvww	xD
" 
"s   )
V ;B	W
(W
Wc                    t        |t              sJ d       |t        |t              sJ d       t        |t              sJ d       |j                  |j                  dk\  rdndd      }|d}d	j                  t        d
||d            }t        ||ddj                  |j                        i      }	 t        || j                        }|j                         j                  d      }
g }|
j!                  d      D ]2  }|st#        j$                  |      d   }t'        |      dk7  s-|d   } n |r|S t        |t(              rt'        |j+                  dg             dk(  r
t-               d|d   v rt/        |d   d       }n|d   d   }d|vr
t-               |d   S # t        $ r)}	t        dj                  |	j                              d}	~	wt        $ r)}	t        dj                  |	j                              d}	~	ww xY w)aX  
        Performs speech recognition on ``audio_data`` (an ``AudioData`` instance), using the Google Speech Recognition API.

        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**.

        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".

        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 tags can be found in this `StackOverflow answer <http://stackoverflow.com/a/14302134>`__.

        Returns the most likely transcription if ``show_all`` is false (the default). Otherwise, returns the raw API response as a JSON dictionary.

        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.
        rC  Nz$``key`` must be ``None`` or a string``language`` must be a string@  r   rO  z'AIzaSyBOti4mM-6x9WDnZIjIeyEU21OpBXqWBgwz0http://www.google.com/speech-api/v2/recognize?{}chromium)clientlangkeyContent-Typezaudio/x-flac; rate={}dataheadersr  recognition request failed: {}!recognition connection failed: {}utf-8
rR   r   alternative
confidencec                     | d   S )Nr  r   )r  s    r   <lambda>z-Recognizer.recognize_google.<locals>.<lambda>^  s    XcdpXq r   )r  
transcript)r.   r   rU  r   rC   r4   r   r   r   r   r   r   reasonr   rg   decodesplitjsonloadsr   dictr7   r   max)r   rq  r  rr  ru  r   urlrequestresponseeresponse_textactual_resultlinerR   best_hypothesiss                  r   recognize_googlezRecognizer.recognize_google(  s"    *i0U2UU{jc2Z4ZZ(C(I*II,,!+!7!74!?T - 
	 ;G@GG	 S
 I 
 #IH_HfHfgqg}g}H~7  A	Uw0F0FGH
 !..w7 !''- 	DZZ%h/F6{a &q		 M)-.#m6G6GWY6Z2[_`2`hyh{b{=77!-">DqrO ,M:1=O.6G6I0I|,,5  	R?FFqxxPQQ 	UBII!((STT	Us$   8F& &	H/$GH$HHc           	         t        |t              sJ d       |t        j                  |       t        |t              sJ d       |t        d |D              sJ d       |j                  d|j                  cxk  rdk  rn ndnt        dt        |j                  d            d	
      }	 ddlm} ddlm} ddl}	ddl}
ddl}	| j&                  r+|
j)                         | j&                  |	j*                  _        ||j/                         }nPt1        d      5 }|j3                  |       |j5                          |j7                  |j8                        }ddd        |ddd      }d|j                  |d}|d|i|d<   |rd|d<   |j?                         jA                  dtC        jD                  |      jG                  d      i|d      }	 |jI                         }|r|S d|vstU        |d         dk(  r
tW               d }|d   D ]!  }||d!   d   d"   jY                         d#z   z  }# |S # t        $ r t        d      w xY w# 1 sw Y   xY w# t:        $ r t=        d      w xY w# |	jJ                  jL                  $ r}t=        |      d}~wtN        $ r)}t=        djQ                  |jR                              d}~ww xY w)$a  
        Performs speech recognition on ``audio_data`` (an ``AudioData`` instance), using the Google Cloud Speech API.

        This function 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. Basically, create a project, enable billing for the project, enable the Google Cloud Speech API for the project, and set up Service Account Key credentials for the project. The result is a JSON file containing the API credentials. The text content of this JSON file is specified by ``credentials_json``. If not specified, the library will try to automatically `find the default API credentials JSON file <https://developers.google.com/identity/protocols/application-default-credentials>`__.

        The recognition language is determined by ``language``, which is a BCP-47 language tag like ``"en-US"`` (US English). A list of supported language tags can be found in the `Google Cloud Speech API documentation <https://cloud.google.com/speech/docs/languages>`__.

        If ``preferred_phrases`` is an iterable 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>`__.

        Returns the most likely transcription if ``show_all`` is False (the default). Otherwise, returns the raw API response as a JSON dictionary.

        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.
        rC  Nz<``credentials_json`` must be ``None`` or a valid JSON stringr  c              3   \   K   | ]$  }t        |t        d       t        d       f       & yw)rr   NrE  )r   preferred_phrasess     r   r   z4Recognizer.recognize_google_cloud.<locals>.<genexpr>x  s0       0Qiz
;LtTVxY]^aYbNc0d  0Qs   *,z/``preferred_phrases`` must be a list of stringsr  i  r   rO  r   )GoogleCredentials)buildrP  speechv1F)credentialscache_discoveryzbmissing google-api-python-client module: ensure that google-api-python-client is set up correctly.FLAC)encodingsampleRateHertzlanguageCodephrasesspeechContextTenableWordTimeOffsetscontentutf8)rA   rz  )bodyz"recognition connection failed: {0}resultsrr   alternativesr   )-r.   r   r  r  r9   AssertionErrorrU  rW  r   rC   r  minoauth2client.clientr  googleapiclient.discoveryr  googleapiclient.errorssocketgoogleapiclient.httpr   getdefaulttimeouthttpDEFAULT_HTTP_TIMEOUT_SECget_application_defaultr^  r   r`  from_streamrO   rJ   r   r  	recognizebase64	b64encoder  executeerrors	HttpErrorr   r4   r  r   r   strip)r   rq  credentials_jsonrr  r  ru  r   r  r  googleapiclientr  api_credentialsr   speech_servicespeech_configr  r  r  r  rR   s                       r   recognize_google_cloudz!Recognizer.recognize_google_cloude  s    *i0U2UU',-(C(I*II (C  0Q  P  0Q  -Q  	D  SD  	D ,,!%)?)?!H5!HcRVX[\f\r\rtyXzN{ - 
	
	E=7) '%%&*B*B*D*L@D@V@V$$='"3"K"K"M 04 LGG,-GGI&7&C&CAFF&KOL
 #8T`efN &,
@V@Vhpq(.79J-KM/*59M12 '')33IvO_O_`iOjOqOqrxOyCz  GT  :U3  V	V(H H_H$HY,?(@A(EM^M`G`
y) 	PF&03LAGGICOOJ	P q rN3q$rrr6L L  	E   D  E  E	E %%// 	"q/! 	VCJJ188TUU	VsT   H3 -A-I =II I/ 3III I,/KJK$KKc                    t        |t              sJ d       t        |t              sJ d       |j                  |j                  dk\  rdndd      }d}t        ||dj                  |      d	d
      }	 t        || j                        }|j                         j                  d      }	t        j                   |	      }
|r|
S d|
vs|
d   
t#               |
d   S # t        $ r)}t        dj                  |j                              d}~wt        $ r)}t        dj                  |j                              d}~ww xY w)a"  
        Performs speech recognition on ``audio_data`` (an ``AudioData`` instance), using the Wit.ai API.

        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.

        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.

        The recognition language is configured in the Wit.ai app settings.

        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.

        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.
        Data must be audio data``key`` must be a stringr  Nr   rO  z$https://api.wit.ai/speech?v=20160526	Bearer {}z	audio/wav)Authorizationr  r  r  r  r  r  _text)r.   r   rU  r   rC   r   r4   r   r   r   r   r  r   rg   r  r  r  r   )r   rq  r  ru  r   r  r  r  r  r  rR   s              r   recognize_witzRecognizer.recognize_wit  s:    *i0K2KK#s#?%??**!+!7!74!?T + 
 5#HHZHZ[^H_q|6}~	Uw0F0FGH
 !..w7M* F]& F7O$;CTCV=Vg  	R?FFqxxPQQ 	UBII!((STT	Us$   6C 	D?&$D

D?$D::D?c                 8   t        |t              sJ d       t        |t              sJ d       t        |t              sJ d       t        | dd      t        | dd      }}d}	 dd	lm} |
        |kD  r]d}	t        |	ddd|d      }
|r        }	 t        |
d      }|j                         j!                  d      }|r|| _        dz   | _        |j'                  dd      }dj                  t)        ||t+        j,                         d            }t.        j0                  dk\  r5t        |t3        j4                  |      dj                  |      ddd       }nUd!j                  t7        |            j9                  d      }|d"z   |z   d#z   }t        ||dj                  |      ddd       }	 t        || j:                        }|j                         j!                  d      }t=        j>                  |      }|r|S d&|vs|d&   d'k7  sd(|vr
tA               |d(   S # t        $ r% 	 dd	lm} n# t        t        f$ r d}d
}Y nw xY wY w xY w# t        $ r)}t        dj                  |j                              d}~wt        $ r)}t        dj                  |j                              d}~ww xY w# t        $ r)}t        d$j                  |j                              d}~wt        $ r)}t        d%j                  |j                              d}~ww xY w))af  
        Performs speech recognition on ``audio_data`` (an ``AudioData`` instance), using the Microsoft Bing Speech API.

        The Microsoft Bing Speech API key is specified by ``key``. Unfortunately, these are not available without `signing up for an account <https://azure.microsoft.com/en-ca/pricing/details/cognitive-services/speech-api/>`__ with Microsoft Azure.

        To get the API key, go to the `Microsoft Azure Portal Resources <https://portal.azure.com/>`__ page, go to "All Resources" > "Add" > "See All" > Search "Bing Speech API > "Create", and fill in the form to make a "Bing Speech API" resource. On the resulting page (which is also accessible from the "All Resources" page in the Azure Portal), go to the "Show Access Keys" page, which will have two API keys, either of which can be used for the `key` parameter. Microsoft Bing Speech API keys are 32-character lowercase hexadecimal strings.

        The recognition language is determined by ``language``, a BCP-47 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://docs.microsoft.com/en-us/azure/cognitive-services/speech/api-reference-rest/bingvoicerecognition#recognition-language>`__ under "Interactive and dictation mode".

        Returns the most likely transcription if ``show_all`` is false (the default). Otherwise, returns the `raw API response <https://docs.microsoft.com/en-us/azure/cognitive-services/speech/api-reference-rest/bingvoicerecognition#sample-responses>`__ as a JSON dictionary.

        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.
        r  r  r  bing_cached_access_tokenNbing_cached_access_token_expiryTr   )	monotonicFz7https://api.cognitive.microsoft.com/sts/v1.0/issueTokenr   z!application/x-www-form-urlencoded0)Content-typeContent-LengthzOcp-Apim-Subscription-Keyr  <   r  zcredential request failed: {}z credential connection failed: {}r  iX  rN  r   rO  zWhttps://speech.platform.bing.com/speech/recognition/interactive/cognitiveservices/v1?{})rr  locale	requestid)r      r  z.audio/wav; codec="audio/pcm"; samplerate=16000chunked)r  r  zTransfer-Encodingz{:X}   
s   
0

r  r  RecognitionStatusSuccessDisplayText)!r.   r   rU  getattrtimer  rJ   RuntimeErrorr   r   r   r   r4   r  r   rg   r  r  r  r   r   uuiduuid4r  version_infor   r   r   r  r   r  r  r   )r   rq  r  rr  ru  access_tokenexpire_timeallow_cachingr  credential_urlcredential_request
start_timecredential_responser  r   r  r  ascii_hex_data_lengthchunked_transfer_encoding_datar  r  rR   s                         r   recognize_bingzRecognizer.recognize_bing  sM    *i0K2KK#s#?%??(C(I*II$+D2Ld$SU\]a  dE  GK  VLk	&& )+";VN!(c C"%-0L " &[
X&-.@"&M#
 /335<<WEL0<-7AC7G4** + 

 hnnox z
 p  v%c

8(<!,!3!3L!A R%.G G %+MM#h-$@$G$G$P!-BW-Lx-WZj-j*c(F!,!3!3L!A R%.Q G	Uw0F0FGH
 !..w7M* F]f,7J0Ky0X\iqw\w  @Q  @S  zSm$$K  	&&/. &" %&	&(  U"#B#I#I!((#STT X"#E#L#LQXX#VWWXJ  	R?FFqxxPQQ 	UBII!((STT	Us~   #H! I 3J7 !	I+H21I2IIIII	J4$I??J4$J//J47	L $K$$L0$LLc                    t        |t              sJ d       t        |t              sJ d       t        |t              sJ d       |j                  |j                  dv rdndd      }d	}t        t        j                               t        t        j                               }}t        t        t        j                                     }	t        j                  t        j                  t        j                  |      |j                  d
      dz   |j                  d
      z   |	j                  d
      z   t        j                         j#                               j%                  d
      }
t'        ||dt)        j*                  ||d      dj-                  ||      dj-                  ||	|
      d      }	 t/        || j0                        }|j;                         j%                  d
      }t)        j<                  |      }|r|S d|vs|d   
t?               |d   d   d   d   S # t2        $ r)}t5        dj-                  |j6                              d}~wt8        $ r)}t5        dj-                  |j6                              d}~ww xY w)au  
        Performs speech recognition on ``audio_data`` (an ``AudioData`` instance), using the Houndify API.

        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".

        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.

        Currently, only English is supported as a recognition language.

        Returns the most likely transcription if ``show_all`` is false (the default). Otherwise, returns the raw API response as a JSON dictionary.

        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.
        r  z``client_id`` must be a stringz``client_key`` must be a string)r  rN  NrN  r   rO  z!https://api.houndify.com/v1/audior     ;zapplication/json)ClientIDUserIDz{};{}z{};{};{})r  zHound-Request-InfozHound-Request-AuthenticationzHound-Client-Authenticationr  r  r  r  Disambiguation
ChoiceDatar   Transcription) r.   r   rU  r   rC   r  r  r/   r  r  urlsafe_b64encodehmacnewurlsafe_b64decoder  hashlibsha256digestr  r   r  dumpsr4   r   r   r   r   r  r   rg   r  r   )r   rq  	client_id
client_keyru  r   r  user_id
request_idrequest_timerequest_signaturer  r  r  r  rR   s                   r   recognize_houndifyzRecognizer.recognize_houndify2  s8    *i0K2KK)S)K+KK*c*M,MM**!+!7!7=!He + 
 2!$**,/TZZ\1B3tyy{+,"44HH((4w'$.1B1B71KKlNaNabiNjj fh
 &/ 	 #H."&**)w-W"X,3NN7J,O+5+<+<YVg+h	7
 	Uw0F0FGH
 !..w7M* F]6)V4D-E-M#%%&'5a8II  	R?FFqxxPQQ 	UBII!((STT	Us$   4H$ $	J-$IJ$JJc                    t        |t              sJ d       t        |t              sJ d       t        |t              sJ d       |j                  |j                  dk\  rdnd|j
                  dk\  rdnd      }dj                  t        d	d
j                  |      dd            }t        ||ddd      }t        j                  dj                  ||      j                  d            j                  d      }	|j                  ddj                  |	             	 t        || j                        }
|
j)                         j                  d      }t+        j,                  |      }|r|S d|vst/        |d         dk  s
d|d   d   vr
t1               g }|d   D ]3  }d|vr
t1               |d   D ]  }d|v s|j3                  |d           5 dj5                  |      S # t         $ r)}t#        dj                  |j$                              d}~wt&        $ r)}t#        dj                  |j$                              d}~ww xY w)a  
        Performs speech recognition on ``audio_data`` (an ``AudioData`` instance), using the IBM Speech to Text API.

        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.

        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.

        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.

        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.
        r  z``username`` must be a stringz``password`` must be a stringrN  Nr   rO  zDhttps://stream.watsonplatform.net/speech-to-text/api/v1/recognize?{}falsez{}_BroadbandModelr   )profanity_filtermodelinactivity_timeoutzaudio/x-flactrue)r  zX-Watson-Learning-Opt-Outr  z{}:{}r  r  zBasic {}r  r  r  r  r,   r  r   r  r  )r.   r   rU  r   rC   r   r4   r   r   r  standard_b64encoder  r  
add_headerr   r   r   r   r  r   rg   r  r  r   r   rQ   r   )r   rq  usernamepasswordrr  ru  r   r  r  authorization_valuer  r  r  rR   transcription	utterancer  s                    r   recognize_ibmzRecognizer.recognize_ibmg  sY    *i0K2KK(C(I*II(C(I*II,,!+!7!75!@e","9"9Q">$A - 
	 U[[\e '(//9"$g
 ] 
 #I*)/8
  %77xQY8Z8a8abi8jkrrsz{?J,=,=>Q,RS	Uw0F0FGH
 !..w7M* F]F"c&*;&<q&@NZ`ajZklmZnDn#%%	* 	CIY.6G6I0I'7 C
:-!((L)ABC	C
 yy''%  	R?FFqxxPQQ 	UBII!((STT	Us$   G$ $	I-$HI$IIr   )r,   r_   )NNN)en-USNNF)Nr#  F)Nr#  NF)F)r#  F)r   r   r   r   r   r  r#  r1  rA  r  r  r  r  r  r  r"  r   r   r   r   r     sU    )NBd6(.T_NBBa"F;-zIV#J[%z3Jj3(r   r   c                     t        d      } | t        j                  j                  t        j                  j	                  t
                    }t        j                         t        j                         }}|dk(  r%|dv r!t        j                  j                  |d      } n|dk(  r%|dv r!t        j                  j                  |d      } n_|dk(  r%|dv r!t        j                  j                  |d	      } n5|dk(  r%|d
v r!t        j                  j                  |d      } nt        d      	 t        j                  | t        j                        st        j                  |       }t        j                  | |j                  t        j                   z         dt        j                         v r<t"        j$                  dk\  rt        j&                         nt        j                  d       | S # t        $ r Y | S w xY w)zdReturns the absolute path of a FLAC converter executable, or raises an OSError if none can be found.flacWindows>   x86i686i786AMD64x86_64zflac-win32.exeDarwinzflac-macLinux>   r'  r(  r)  zflac-linux-x86>   r*  r+  zflac-linux-x86_64zFLAC conversion utility not available - consider installing the FLAC command line application by running `apt-get install flac` or your operating system's equivalent)r   r   sync)shutil_whichr   r  rX  rg  rZ  platformsystemmachiner   OSErroraccessX_OKstatchmodst_modeS_IEXECr  r  r.  )r   	base_pathr1  r2  	stat_infos        r   r   r     s   !&)NGGOOBGGOOH$=>	"//+X-=-=-?Y7.X#XWW\\)5EFNxG/Y$YWW\\)Z@Nw7.E#EWW\\)5EFNw7.A#AWW\\)5HIN  B  C  C
 yy1/IHH^Y%6%6%EF(//++ --7	RYYv=N  D s   +B<G) )	G65G6c                 Z   t        j                  d      }|j                  t         j                  j                        D ]j  }t         j                  j                  ||       }t         j                  j                  |      sCt        j                  |t         j                        sh|c S  y)zDPython 2 compatibility: backport of ``shutil.which()`` from Python 3PATHN)	r   getenvr  r  pathsepr   rf  r4  r5  )pgmr  ps      r   r/  r/    sj    99VDZZ( GGLLC 77>>!1bgg!6Hr   c                   6    e Zd ZdZd	dZd Zd Zd Zd Zd Z	y)
r^  zLimited replacement for ``tempfile.NamedTemporaryFile``, except unlike ``tempfile.NamedTemporaryFile``, the file can be opened again while it's currently open, even on Windows.c                     || _         y r_   )mode)r   rD  s     r   r   z#PortableNamedTemporaryFile.__init__  s	    	r   c                     dd l }|j                         \  }}t        j                  || j                        | _        || _        | S )Nr   )tempfilemkstempr   fdopenrD  _filerO   )r   rF  file_descriptor	file_paths       r   r"   z$PortableNamedTemporaryFile.__enter__  s<    %-%5%5%7"YY		:
 	r   c                 v    | j                   j                          t        j                  | j                         y r_   )rI  r`   r   removerO   r$   s       r   r(   z#PortableNamedTemporaryFile.__exit__  s"    


		$))r   c                 :     | j                   j                  |i |S r_   )rI  r   r   argskwargss      r   r   z PortableNamedTemporaryFile.write      tzz000r   c                 :     | j                   j                  |i |S r_   )rI  r_  rO  s      r   r_  z%PortableNamedTemporaryFile.writelines  s    $tzz$$d5f55r   c                 :     | j                   j                  |i |S r_   )rI  r`  rO  s      r   r`  z PortableNamedTemporaryFile.flush  rR  r   N)zw+b)
r   r   r   rl   r   r"   r(   r   r_  r`  r   r   r   r^  r^    s&     {161r   r^  c           
         |j                  dd      }d}	 t        j                         j                  }|j	                  d      |vrn3|t        j                         j                  }d|j	                  d      z   dz   dz   d	z   dz   d
z   |j	                  d      z   dz   |j	                  d      z   dz   dz   |j	                  d      z   dz   dz   dz   dz   |z   dz   dz   |j	                  d      z   dz   }	t        ||	dj                  |      t        t        |	            ddj                  |      d      }
t        |
d      }|j                         j                  d      }t!        j"                  |      }|r|S d|vsd|d   vs|d   d   dk7  r
t%               |d   d   S # t        $ r)}t        dj                  |j                              d }~wt        $ r)}t        dj                  |j                              d }~ww xY w)NrN  r   rO  zhttps://api.api.ai/v1/queryr  s   --r  s0   Content-Disposition: form-data; name="request"
s    Content-Type: application/json
s    {"v": "20150910", "sessionId": "s   ", "lang": "s   "}
sH   Content-Disposition: form-data; name="voiceData"; filename="audio.wav"
s   Content-Type: audio/wav
s   --
r  z100-continuez multipart/form-data; boundary={})r  r  Expectr  r  
   r  r  r  status	errorTypesuccessrR   resolvedQuery)r   r  r  hexr  r   r4   rU  r   r   r   r   r  r   rg   r  r  r  r   )r   rq  client_access_tokenrr  
session_idru  r   r  boundaryr  r  r  r  r  rR   s                  r   recognize_apir`    s   &&E&KH
'C
::<##??7#83U  

(8(8:8??7++g58oo  sX  X  [b  b  eO  O  R\  Rc  Rc  dk  Rl  l  oB  B  EM  ET  ET  U\  E]  ]  `j  j  mr  r  u}  uD  uD  EL  uM  M  PW  W  Zk  k  nL  L  OV  V  Ya  a  dk  k  ns  s  v~  vE  vE  FM  vN  N  QZ  ZDc@R@RSf@g{~  @C  DH  @I  |J  Vd  vX  v_  v_  `h  vi  /j  kGGR0 MMO**73MZZ&FvF84D!DxHXYdHeirHr!!(O,, `.N.U.UVWV^V^._!``b-P-W-WXYX`X`-a bbbs$   9F& &	H/$GH$HH)enNF)1rl   r   r   r  r   r   r   r  r   r  r  r  r=  r0  r6  r
  r  r  r  
__author__rM   __license__urllibr   urllib2r   r   r   r   rJ   urllib.parseurllib.requesturllib.errorr9   r
   r   r   rn   r   r*   rp   r   r   r   r/  r^  WavFiler`  classmethodr   r   r   <module>rk     s   p 	 	 
               $
1 == (y ' $9 # )	 (?& ?p, p,fq qhk k\L( L(^B1 1B -( '}5
 A'  1&/001s   C! !C?>C?