o
    Þ­j)3  ã                   @   s¸   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mZmZ d dl	m
Z
mZmZ d dlmZmZmZ ddgZe e¡Ze e ¡ ¡ G dd„ dƒZG d	d„ dƒZG d
d„ deƒZdS )é    N)Ú_fallback_deprecated_langÚ	tts_langs)Ú	TokenizerÚpre_processorsÚtokenizer_cases)Ú_clean_tokensÚ	_minimizeÚ_translate_urlÚgTTSÚ	gTTSErrorc                   @   s   e Zd ZdZdZdZdS )ÚSpeedznRead Speed

    The Google TTS Translate API supports two speeds:
        Slow: True
        Normal: None
    TN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚSLOWÚNORMAL© r   r   úE/var/www/html/CropPilot/venv/lib/python3.10/site-packages/gtts/tts.pyr      s    r   c                
   @   sš   e Zd ZdZdZddddœZdZdd	d
dejej	ej
ejgeejejejejgƒjdf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S )r
   ac
  gTTS -- Google Text-to-Speech.

    An interface to Google Translate's Text-to-Speech API.

    Args:
        text (string): The text to be read.
        tld (string): Top-level domain for the Google Translate host,
            i.e `https://translate.google.<tld>`. Different Google domains
            can produce different localized 'accents' for a given
            language. This is also useful when ``google.com`` might be blocked
            within a network but a local or different Google host
            (e.g. ``google.com.hk``) is not. Default is ``com``.
        lang (string, optional): The language (IETF language tag) to
            read the text in. Default is ``en``.
        slow (bool, optional): Reads text more slowly. Defaults to ``False``.
        lang_check (bool, optional): Strictly enforce an existing ``lang``,
            to catch a language error early. If set to ``True``,
            a ``ValueError`` is raised if ``lang`` doesn't exist.
            Setting ``lang_check`` to ``False`` skips Web requests
            (to validate language) and therefore speeds up instantiation.
            Default is ``True``.
        pre_processor_funcs (list): A list of zero or more functions that are
            called to transform (pre-process) text before tokenizing. Those
            functions must take a string and return a string. Defaults to::

                [
                    pre_processors.tone_marks,
                    pre_processors.end_of_line,
                    pre_processors.abbreviations,
                    pre_processors.word_sub
                ]

        tokenizer_func (callable): A function that takes in a string and
            returns a list of string (tokens). Defaults to::

                Tokenizer([
                    tokenizer_cases.tone_marks,
                    tokenizer_cases.period_comma,
                    tokenizer_cases.colon,
                    tokenizer_cases.other_punctuation
                ]).run

        timeout (float or tuple, optional): Seconds to wait for the server to
            send data before giving up, as a float, or a ``(connect timeout,
            read timeout)`` tuple. ``None`` will wait forever (default).

    See Also:
        :doc:`Pre-processing and tokenizing <tokenizer>`

    Raises:
        AssertionError: When ``text`` is ``None`` or empty; when there's nothing
            left to speak after pre-processing, tokenizing and cleaning.
        ValueError: When ``lang_check`` is ``True`` and ``lang`` is not supported.
        RuntimeError: When ``lang_check`` is ``True`` but there's an error loading
            the languages dictionary.

    éd   zhttp://translate.google.com/znMozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36z/application/x-www-form-urlencoded;charset=utf-8)ÚRefererz
User-AgentzContent-TypeÚjQ1olcÚcomÚenFTNc	              
   C   sö   t tƒ ƒ ¡ D ]\}	}
|	dkrqt d|	|
¡ q|sJ dƒ‚|| _|| _|| _|| _| jret	|ƒ| _zt
ƒ }| j|vrAtd| ƒ‚W n" tyd } ztjt|ƒdd� t t|ƒ¡ W Y d }~nd }~ww |rltj| _ntj| _|| _|| _|| _d S )NÚselfz%s: %szNo text to speakzLanguage not supported: %sT)Úexc_info)ÚdictÚlocalsÚitemsÚlogÚdebugÚtextÚtldÚ
lang_checkÚlangr   r   Ú
ValueErrorÚRuntimeErrorÚstrÚwarningr   r   Úspeedr   Úpre_processor_funcsÚtokenizer_funcÚtimeout)r   r!   r"   r$   Úslowr#   r*   r+   r,   ÚkÚvÚlangsÚer   r   r   Ú__init__f   s6   

ÿ€þ

zgTTS.__init__c                 C   s’   |  ¡ }| jD ]}t d|¡ ||ƒ}qt|ƒ| jkr t|gƒS t d| j¡ |  |¡}t|ƒ}g }|D ]}|t|d| jƒ7 }q4dd„ |D ƒ}|S )Nzpre-processing: %sztokenizing: %sú c                 S   s   g | ]}|r|‘qS r   r   )Ú.0Útr   r   r   Ú
<listcomp>À   s    z"gTTS._tokenize.<locals>.<listcomp>)	Ústripr*   r   r    ÚlenÚGOOGLE_TTS_MAX_CHARSr   r+   r   )r   r!   ÚppÚtokensÚ
min_tokensr5   r   r   r   Ú	_tokenize§   s   



zgTTS._tokenizec                 C   sš   t | jdd�}|  | j¡}t dt|ƒ¡ t dt|ƒ¡ |s#J dƒ‚g }t|ƒD ]!\}}|  	|¡}t d||¡ t
jd||| jd�}| | ¡ ¡ q)|S )	zÒCreated the TTS API the request(s) without sending them.

        Returns:
            list: ``requests.PreparedRequests_``. <https://2.python-requests.org/en/master/api/#requests.PreparedRequest>`_``.
        z(_/TranslateWebserverUi/data/batchexecute)r"   Úpathztext_parts: %sztext_parts: %izNo text to send to TTS APIzdata-%i: %sÚPOST)ÚmethodÚurlÚdataÚheaders)r	   r"   r=   r!   r   r    r'   r8   Ú	enumerateÚ_package_rpcÚrequestsÚRequestÚGOOGLE_TTS_HEADERSÚappendÚprepare)r   Útranslate_urlÚ
text_partsÚprepared_requestsÚidxÚpartrB   Úrr   r   r   Ú_prepare_requestsÄ   s&   ÿ
üzgTTS._prepare_requestsc                 C   sP   || j | jdg}tj|dd�}| j|d dggg}tj|dd�}d tj |¡¡S )NÚnull)ú,ú:)Ú
separatorsÚgenericz	f.req={}&)	r$   r)   ÚjsonÚdumpsÚGOOGLE_TTS_RPCÚformatÚurllibÚparseÚquote)r   r!   Ú	parameterÚescaped_parameterÚrpcÚespaced_rpcr   r   r   rE   ç   s
   zgTTS._package_rpcc                 C   s   dd„ |   ¡ D ƒS )z—Get TTS API request bodies(s) that would be sent to the TTS API.

        Returns:
            list: A list of TTS API request bodies to make.
        c                 S   s   g | ]}|j ‘qS r   )Úbody)r4   Úprr   r   r   r6   õ   s    z#gTTS.get_bodies.<locals>.<listcomp>)rQ   )r   r   r   r   Ú
get_bodiesï   s   zgTTS.get_bodiesc                 c   sš  � zt jj t jjjj¡ W n   Y |  ¡ }t|ƒD ]¯\}}zAt  ¡ �}|j	|dt
j ¡ | jd�}W d  ƒ n1 s<w   Y  t d||jj¡ t d||jj¡ t d||j¡ | ¡  W n4 t jjy{ } zt t|ƒ¡ t| |d�‚d}~w t jjy” } zt t|ƒ¡ t| d�‚d}~ww |jd	d
�D ](}| d¡}d|v rÃt d|¡}	|	r½|	 d¡ d¡}
t |
¡V  q›t| |d�‚q›t d|¡ qdS )z‘Do the TTS API request(s) and stream bytes

        Raises:
            :class:`gTTSError`: When there's an error with the API request.

        F)ÚrequestÚverifyÚproxiesr,   Nzheaders-%i: %sz
url-%i: %szstatus-%i: %s)ÚttsÚresponse)rh   i   )Ú
chunk_sizezutf-8r   zjQ1olc","\[\\"(.*)\\"]é   Úasciizpart-%i created) rF   ÚpackagesÚurllib3Údisable_warningsÚ
exceptionsÚInsecureRequestWarningrQ   rD   ÚSessionÚsendr[   re   Ú
getproxiesr,   r   r    rC   rA   Ústatus_codeÚraise_for_statusÚ	HTTPErrorr'   r   ÚRequestExceptionÚ
iter_linesÚdecodeÚreÚsearchÚgroupÚencodeÚbase64Ú	b64decode)r   rM   rN   rc   ÚsrP   r1   ÚlineÚdecoded_lineÚaudio_searchÚas_bytesr   r   r   Ústream÷   sT   €	
ÿ
üþ	€
€ý
ø	ÛzgTTS.streamc              
   C   sb   zt |  ¡ ƒD ]\}}| |¡ t d||¡ qW dS  ttfy0 } ztdt|ƒ ƒ‚d}~ww )aQ  Do the TTS API request(s) and write bytes to a file-like object.

        Args:
            fp (file object): Any file-like object to write the ``mp3`` to.

        Raises:
            :class:`gTTSError`: When there's an error with the API request.
            TypeError: When ``fp`` is not a file-like object that takes bytes.

        zpart-%i written to %sz<'fp' is not a file-like object or it does not take bytes: %sN)rD   r†   Úwriter   r    ÚAttributeErrorÚ	TypeErrorr'   )r   ÚfprN   Údecodedr1   r   r   r   Úwrite_to_fp/  s   
þ
ÿ€ÿzgTTS.write_to_fpc                 C   sR   t t|ƒdƒ�}|  |¡ | ¡  t d|¡ W d  ƒ dS 1 s"w   Y  dS )zôDo the TTS API request and write result to file.

        Args:
            savefile (string): The path and file name to save the ``mp3`` to.

        Raises:
            :class:`gTTSError`: When there's an error with the API request.

        ÚwbzSaved to %sN)Úopenr'   rŒ   Úflushr   r    )r   ÚsavefileÚfr   r   r   ÚsaveD  s
   

"ýz	gTTS.save)r   r   r   r   r9   rH   rY   r   Ú
tone_marksÚend_of_lineÚabbreviationsÚword_subr   r   Úperiod_commaÚcolonÚother_punctuationÚrunr2   r=   rQ   rE   rd   r†   rŒ   r’   r   r   r   r   r
   !   sD    :ûüüÿ
ëA#8c                       s,   e Zd ZdZd‡ fdd„	Zddd„Z‡  ZS )r   zAException that uses context to present a meaningful error messageNc                    sb   |  dd ¡| _|  dd ¡| _|r|| _n| jd ur#|  | j| j¡| _nd | _tt| ƒ | j¡ d S )Nrh   ri   )Úpoprh   ÚrspÚmsgÚ	infer_msgÚsuperr   r2   )r   r�   Úkwargs©Ú	__class__r   r   r2   W  s   
zgTTSError.__init__c                 C   s¬   d}|du rd}|j dkrt|j d�}d |¡}n7|j}|j}d ||¡}|dkr,d	}n$|d
kr<|j dkr<d |j ¡}n|dkrJ|jsJd| jj }n|dkrPd}d ||¡S )zyAttempt to guess what went wrong by using known
        information (e.g. http response) and observed behaviour

        ÚUnknownNzFailed to connectr   )r"   zHost '{}' is not reachablez{:d} ({}) from TTS APIi“  z!Bad token or upstream API changesi”  zUnsupported tld '{}'éÈ   z6No audio stream in response. Unsupported language '%s'iô  z$Upstream API error. Try again later.z{}. Probable cause: {})r"   r	   rZ   ru   Úreasonr#   rh   r$   )r   rh   rœ   ÚcauseÚpremiseÚhostÚstatusr¥   r   r   r   rž   b  s,   

€ÿÿzgTTSError.infer_msg)N)r   r   r   r   r2   rž   Ú__classcell__r   r   r¡   r   r   T  s    )r   rW   Úloggingr{   r[   rF   Ú	gtts.langr   r   Úgtts.tokenizerr   r   r   Ú
gtts.utilsr   r   r	   Ú__all__Ú	getLoggerr   r   Ú
addHandlerÚNullHandlerr   r
   Ú	Exceptionr   r   r   r   r   Ú<module>   s"   
  5