
    i'                    j   d dl mZ d dlZd dlmZmZmZmZ d dlm	Z	m
Z
 d dlmZ d dlmZmZ d dlmZ d dlmZ d d	lmZmZ  G d
 de      Z G d de      Z G d de      Zed   Zeeef   ZdZ G d d      Zddd d	 	 	 	 	 	 	 	 	 ddZ G d d      Z ddZ!	 	 	 	 	 ded	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ"y)     )annotationsN)DictLiteralOptional	TypedDict)	HTTPErrorURLError)	urlencode)Requesturlopen)NotRequired)	AudioData)RequestErrorUnknownValueErrorc                  "    e Zd ZU ded<   ded<   y)Alternativestr
transcriptfloat
confidenceN__name__
__module____qualname____annotations__     c/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/speech_recognition/recognizers/google.pyr   r      s    Or   r   c                  "    e Zd ZU ded<   ded<   y)Resultlist[Alternative]alternativeboolfinalNr   r   r   r   r    r       s    ""Kr   r    c                  "    e Zd ZU ded<   ded<   y)GoogleResponsezlist[Result]resultzNotRequired[int]result_indexNr   r   r   r   r&   r&      s    ""r   r&   )r      z-http://www.google.com/speech-api/v2/recognizec                  Z    e Zd Z	 	 	 	 	 	 	 	 	 	 ddZd	dZd
dZddZddZedd       Z	y)RequestBuilderc               <    || _         || _        || _        || _        y Nendpointkeylanguagefilter_level)selfr/   r0   r1   r2   s        r   __init__zRequestBuilder.__init__%   s!     ! (r   c                    t        |t              st        d      | j                         }| j	                  |      }| j                  |      }t        |||      }|S )Nz!``audio_data`` must be audio data)dataheaders)
isinstancer   
ValueError	build_urlbuild_headers
build_datar   )r3   
audio_dataurlr7   	flac_datarequests         r   buildzRequestBuilder.build2   sU    *i0@AAnn$$Z0OOJ/	#Iw?r   c                    t        d| j                  | j                  | j                  d      }| j                   d| S )a*  
        >>> builder = RequestBuilder(endpoint="http://www.google.com/speech-api/v2/recognize", key="awesome-key", language="en-US", filter_level=0)
        >>> builder.build_url()
        'http://www.google.com/speech-api/v2/recognize?client=chromium&lang=en-US&key=awesome-key&pFilter=0'
        chromium)clientlangr0   pFilter?)r
   r1   r0   r2   r/   )r3   paramss     r   r:   zRequestBuilder.build_url<   sD     $xx,,	
 --&**r   c                ,    |j                   }dd| i}|S )z
        >>> builder = RequestBuilder(endpoint="", key="", language="", filter_level=1)
        >>> audio_data = AudioData(b"", 16_000, 1)
        >>> builder.build_headers(audio_data)
        {'Content-Type': 'audio/x-flac; rate=16000'}
        zContent-Typezaudio/x-flac; rate=sample_rate)r3   r=   rater7   s       r   r;   zRequestBuilder.build_headersL   s&     %%!%8#?@r   c                ^    |j                  | j                  |j                        d      }|S )N   )convert_rateconvert_width)get_flac_datato_convert_raterK   )r3   r=   r?   s      r   r<   zRequestBuilder.build_dataW   s6    ,,--j.D.DE - 
	 r   c                    | dk\  rdS dS )zAudio samples must be at least 8 kHz

        >>> RequestBuilder.to_convert_rate(16_000)
        >>> RequestBuilder.to_convert_rate(8_000)
        >>> RequestBuilder.to_convert_rate(7_999)
        8000
        i@  Nr   rJ   s    r   rR   zRequestBuilder.to_convert_rate^   s     #d*t44r   N)
r/   r   r0   r   r1   r   r2   ProfanityFilterLevelreturnNone)r=   r   rU   r   )rU   r   )r=   r   rU   RequestHeaders)r=   r   rU   bytes)rK   intrU   zOptional[int])
r   r   r   r4   rA   r:   r;   r<   staticmethodrR   r   r   r   r+   r+   $   sa    ) ) 	)
 ) +) 
)+ 	 5 5r   r+   en-US)r0   r1   r2   c                    t        |t              st        d      |t        |t              st        d      |d}t        | |||      S )Nz``language`` must be a stringz$``key`` must be ``None`` or a stringz'AIzaSyBOti4mM-6x9WDnZIjIeyEU21OpBXqWBgwr.   )r8   r   r9   r+   r.   s       r   create_request_builderr]   j   sW     h$899
z#s3?@@
{7!	 r   c                  @    e Zd ZddZddZedd       Zed	d       Zy)
OutputParserc                    || _         || _        y r-   show_allwith_confidence)r3   rb   rc   s      r   r4   zOutputParser.__init__   s     .r   c                    | j                  |      }| j                  r|S | j                  |d         }|j                  dd      }| j                  r|d   |fS |d   S )Nr"   r   g      ?r   )convert_to_resultrb   find_best_hypothesisgetrc   )r3   response_textactual_resultbest_hypothesisr   s        r   parsezOutputParser.parse   so    ..}===  33-(

 %((s;
"<0*<<|,,r   c                    | j                  d      D ]]  }|st        j                  |      d   }t        |      dk7  s-t        |d   j	                  dg             dk(  r
t               |d   c S  t               )a  
        >>> response_text = '''{"result":[]}
        ... {"result":[{"alternative":[{"transcript":"one two three","confidence":0.49585345},{"transcript":"1 2","confidence":0.42899391}],"final":true}],"result_index":0}
        ... '''
        >>> OutputParser.convert_to_result(response_text)
        {'alternative': [{'transcript': 'one two three', 'confidence': 0.49585345}, {'transcript': '1 2', 'confidence': 0.42899391}], 'final': True}

        >>> OutputParser.convert_to_result("")
        Traceback (most recent call last):
          ...
        speech_recognition.exceptions.UnknownValueError
        >>> OutputParser.convert_to_result('\n{"result":[]}')
        Traceback (most recent call last):
          ...
        speech_recognition.exceptions.UnknownValueError
        >>> OutputParser.convert_to_result('{"result":[{"foo": "bar"}]}')
        Traceback (most recent call last):
          ...
        speech_recognition.exceptions.UnknownValueError
        >>> OutputParser.convert_to_result('{"result":[{"alternative": []}]}')
        Traceback (most recent call last):
          ...
        speech_recognition.exceptions.UnknownValueError
        
r'   r   r"   )splitjsonloadslenrg   r   )rh   liner'   s      r   re   zOutputParser.convert_to_result   s}    6 "''- 	!D#'::d#3H#=F6{avay}}]B78A=+--ay 	!  !!r   c                R    d| v rt        | d       }n| d   }d|vr
t               |S )a  
        >>> alternatives = [{"transcript": "one two three", "confidence": 0.42899391}, {"transcript": "1 2", "confidence": 0.49585345}]
        >>> OutputParser.find_best_hypothesis(alternatives)
        {'transcript': 'one two three', 'confidence': 0.42899391}

        >>> alternatives = [{"confidence": 0.49585345}]
        >>> OutputParser.find_best_hypothesis(alternatives)
        Traceback (most recent call last):
          ...
        speech_recognition.exceptions.UnknownValueError
        r   c                    | d   S )Nr   r   )r"   s    r   <lambda>z3OutputParser.find_best_hypothesis.<locals>.<lambda>   s    L(A r   )r0   r   r   )maxr   )alternativesrj   s     r   rf   z!OutputParser.find_best_hypothesis   s@     <' "AO +1oO.#%%r   N)rb   r#   rc   r#   rU   rV   )rh   r   )rh   r   rU   r    )rw   r!   rU   r   )r   r   r   r4   rk   rZ   re   rf   r   r   r   r_   r_      s5    /- "" ""H  r   r_   c                &   	 t        | |      }|j                         j                  d      S # t        $ r)}t        dj                  |j                              d }~wt
        $ r)}t        dj                  |j                              d }~ww xY w)Ntimeoutzrecognition request failed: {}z!recognition connection failed: {}zutf-8)r   r   r   formatreasonr	   readdecode)r@   rz   responsees       r   obtain_transcriptionr      s    
7G4 ==?!!'**  N;BB188LMM 
/66qxx@
 	

s    . 	B$AB'$BB)r/   c                   t        ||||      }|j                  |      }	t        |	| j                        }
t	        ||      }|j                  |
      S )a  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>`__.

    The profanity filter level can be adjusted with ``pfilter``: 0 - No filter, 1 - Only shows the first character and replaces the rest with asterisks. The default is level 0.

    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.   ry   ra   )r]   rA   r   operation_timeoutr_   rk   )
recognizerr=   r0   r1   pfilterrb   rc   r/   request_builderr@   rh   output_parsers               r   recognize_legacyr      sb    2 -sXGO ##J/G(55M !?M }--r   )
r/   r   r0   
str | Noner1   r   r2   rT   rU   r+   )r@   r   rz   rY   rU   r   )Nr[   r   FF)r=   r   r0   r   r1   r   r   rT   rb   r#   rc   r#   r/   r   )#
__future__r   ro   typingr   r   r   r   urllib.errorr   r	   urllib.parser
   urllib.requestr   r   typing_extensionsr   speech_recognition.audior   speech_recognition.exceptionsr   r   r   r    r&   rT   r   rW   ENDPOINTr+   r]   r_   r   r   r   r   r   <module>r      s(   "  5 5 , " + ) . I) 
Y 
#Y #
 t} c3h:C5 C5R )* 
 	
 ' ,S Sl	+ $%!%. %.%. 
%. 	%.
 "%. %. %. %.r   