o
    Ö­jÄ'  ã                   @  s"  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„ deƒZG dd„ deƒZG dd„ deƒZed Zeeef ZdZG dd„ dƒZddd dœd2dd„ZG d d!„ d!ƒZ d3d&d'„Z!			 	(	(d4ed)œd5d0d1„Z"dS )6é    )Ú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< dS )ÚAlternativeÚstrÚ
transcriptÚfloatÚ
confidenceN©Ú__name__Ú
__module__Ú__qualname__Ú__annotations__© r   r   úb/var/www/html/CropPilot/venv/lib/python3.10/site-packages/speech_recognition/recognizers/google.pyr      ó   
 r   c                   @  r   )ÚResultúlist[Alternative]ÚalternativeÚboolÚfinalNr   r   r   r   r   r      r   r   c                   @  r   )ÚGoogleResponsezlist[Result]ÚresultzNotRequired[int]Úresult_indexNr   r   r   r   r   r#      r   r#   )r   é   z-http://www.google.com/speech-api/v2/recognizec                   @  sL   e Zd Zdd	d
„Zddd„Zd dd„Zd!dd„Zd"dd„Zed#dd„ƒZ	dS )$ÚRequestBuilderÚendpointr   ÚkeyÚlanguageÚfilter_levelÚProfanityFilterLevelÚreturnÚNonec                C  s   || _ || _|| _|| _d S ©N©r(   r)   r*   r+   )Úselfr(   r)   r*   r+   r   r   r   Ú__init__%   s   
zRequestBuilder.__init__Ú
audio_datar   r
   c                 C  s@   t |tƒs	tdƒ‚|  ¡ }|  |¡}|  |¡}t|||d�}|S )Nz!``audio_data`` must be audio data)ÚdataÚheaders)Ú
isinstancer   Ú
ValueErrorÚ	build_urlÚbuild_headersÚ
build_datar
   )r1   r3   Úurlr5   Ú	flac_dataÚrequestr   r   r   Úbuild2   s   


zRequestBuilder.buildc                 C  s(   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Úlangr)   ÚpFilterú?)r	   r*   r)   r+   r(   )r1   Úparamsr   r   r   r8   <   s   üÿzRequestBuilder.build_urlÚRequestHeadersc                 C  s   |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)r1   r3   Úrater5   r   r   r   r9   L   s   zRequestBuilder.build_headersÚbytesc                 C  s   |j |  |j¡dd�}|S )Né   )Úconvert_rateÚconvert_width)Úget_flac_dataÚto_convert_raterG   )r1   r3   r<   r   r   r   r:   W   s
   
þzRequestBuilder.build_datarG   ÚintúOptional[int]c                 C  s   | dkrdS dS )zÒAudio 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   rF   r   r   r   rN   ^   s   	zRequestBuilder.to_convert_rateN)
r(   r   r)   r   r*   r   r+   r,   r-   r.   )r3   r   r-   r
   )r-   r   )r3   r   r-   rE   )r3   r   r-   rI   )rG   rO   r-   rP   )
r   r   r   r2   r>   r8   r9   r:   ÚstaticmethodrN   r   r   r   r   r'   $   s    





r'   úen-US)r)   r*   r+   r(   r   r)   ú
str | Noner*   r+   r,   r-   c                 C  sH   t |tƒs	tdƒ‚|d urt |tƒstdƒ‚|d u rd}t| |||d�S )Nz``language`` must be a stringz$``key`` must be ``None`` or a stringz'AIzaSyBOti4mM-6x9WDnZIjIeyEU21OpBXqWBgwr0   )r6   r   r7   r'   r0   r   r   r   Úcreate_request_builderj   s   
ürT   c                   @  s<   e Zd Zddd„Zdd
d„Zeddd„ƒZeddd„ƒZdS )ÚOutputParserÚshow_allr!   Úwith_confidencer-   r.   c                C  s   || _ || _d S r/   ©rV   rW   )r1   rV   rW   r   r   r   r2   �   s   
zOutputParser.__init__Úresponse_textr   c                 C  sH   |   |¡}| jr
|S |  |d ¡}| dd¡}| jr |d |fS |d S )Nr    r   g      à?r   )Úconvert_to_resultrV   Úfind_best_hypothesisÚgetrW   )r1   rY   Úactual_resultÚbest_hypothesisr   r   r   r   Úparse…   s   
ÿzOutputParser.parser   c                 C  s`   |   d¡D ]'}|s
qt |¡d }t|ƒdkr,t|d  dg ¡ƒdkr&tƒ ‚|d   S q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Úlenr\   r   )rY   Úliner$   r   r   r   rZ   ”   s   ýzOutputParser.convert_to_resultÚalternativesr   r   c                 C  s4   d| v rt | dd„ 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                 S  s   | d S )Nr   r   )r    r   r   r   Ú<lambda>Ì   s    z3OutputParser.find_best_hypothesis.<locals>.<lambda>)r)   r   r   )Úmaxr   )rf   r^   r   r   r   r[   ¹   s   þz!OutputParser.find_best_hypothesisN)rV   r!   rW   r!   r-   r.   )rY   r   )rY   r   r-   r   )rf   r   r-   r   )r   r   r   r2   r_   rQ   rZ   r[   r   r   r   r   rU   €   s    

$rU   r=   r
   ÚtimeoutrO   c              
   C  sn   zt | |d�}W n' ty } ztd |j¡ƒ‚d }~w ty/ } ztd |j¡ƒ‚d }~ww | ¡  d¡S )N©ri   zrecognition request failed: {}z!recognition connection failed: {}zutf-8)r   r   r   ÚformatÚreasonr   ÚreadÚdecode)r=   ri   ÚresponseÚer   r   r   Úobtain_transcriptionÖ   s   €
ÿ€ÿrq   F)r(   r3   r   ÚpfilterrV   r!   rW   c                C  s>   t ||||d�}| |¡}	t|	| jd�}
t||d�}| |
¡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.
    r0   rj   rX   )rT   r>   rq   Úoperation_timeoutrU   r_   )Ú
recognizerr3   r)   r*   rr   rV   rW   r(   Úrequest_builderr=   rY   Úoutput_parserr   r   r   Úrecognize_legacyâ   s   ÿ
ÿÿ
rw   )
r(   r   r)   rS   r*   r   r+   r,   r-   r'   )r=   r
   ri   rO   r-   r   )NrR   r   FF)r3   r   r)   rS   r*   r   rr   r,   rV   r!   rW   r!   r(   r   )#Ú
__future__r   rb   Útypingr   r   r   r   Úurllib.errorr   r   Úurllib.parser	   Úurllib.requestr
   r   Útyping_extensionsr   Úspeech_recognition.audior   Úspeech_recognition.exceptionsr   r   r   r   r#   r,   r   rE   ÚENDPOINTr'   rT   rU   rq   rw   r   r   r   r   Ú<module>   s<    Iû
Vù	÷