o
    1_B=                     @   s   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mZ ddlm	Z	m
Z
 ddlmZ ddlmZmZmZmZmZmZmZmZ ddlmZmZmZ dZd	ZG d
d dZdS )zB
A Translation module.

You can translate text using this module.
    N)Timeout)urlsutils)TokenAcquirer)DEFAULT_CLIENT_SERVICE_URLSDEFAULT_FALLBACK_SERVICE_URLSDEFAULT_USER_AGENT	LANGCODES	LANGUAGESSPECIAL_CASESDEFAULT_RAISE_EXCEPTION
DUMMY_DATA)
TranslatedDetectedTranslatedPart)encafrMkEWBcc                   @   s   e Zd ZdZeeeddddfdeje	e
jf defddZd	e	d
e	de	fddZdd Zd	e	d
e	de	fddZdd Zdd Zd d	e	fddZd ddZd	e	fddZdd ZdS )!
Translatora  Google Translate ajax API implementation class

    You have to create an instance of Translator to use this API

    :param service_urls: google translate url list. URLs will be used randomly.
                         For example ``['translate.google.com', 'translate.google.co.kr']``
                         To preferably use the non webapp api, service url should be translate.googleapis.com
    :type service_urls: a sequence of strings

    :param user_agent: the User-Agent header to send when making requests.
    :type user_agent: :class:`str`

    :param proxies: proxies configuration.
                    Dictionary mapping protocol or protocol and host to the URL of the proxy
                    For example ``{'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}``
    :type proxies: dictionary

    :param timeout: Definition of timeout for httpx library.
                    Will be used for every request.
    :type timeout: number or a double of numbers
    :param proxies: proxies configuration.
                    Dictionary mapping protocol or protocol and host to the URL of the proxy
                    For example ``{'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}``
    :param raise_exception: if `True` then raise exception if smth will go wrong
    :param http2: whether to use HTTP2 (default: True)
    :param use_fallback: use a fallback method
    :type raise_exception: boolean
    NTFproxiestimeoutc                 C   s   t j|d| _|d ur|| j_| jj|dd |d ur!|| j_|r*t| _d| _	n|| _d| _	t
| j| jd d| _|| _d S )N)http2zhttps://translate.google.com)z
User-AgentReferergtxztw-obr   )clienthost)httpxClientr   r   headersupdater   r   service_urlsclient_typer   token_acquirerraise_exception)selfr!   
user_agentr$   r   r   r   use_fallback r(   M/var/www/html/env_mimamsha/lib/python3.10/site-packages/googletrans/client.py__init__<   s&   
zTranslator.__init__textdestsrcc                 C   s2   t jtt j|||dgd ggddd dgggddS )NT),:)
separatorsgeneric)jsondumpsRPC_ID)r%   r+   r,   r-   r(   r(   r)   _build_rpc_request\   s   zTranslator._build_rpc_requestc                 C   s$   t | jdkr| jd S t| jS )N   r   )lenr!   randomchoice)r%   r(   r(   r)   _pick_service_urlf   s   
zTranslator._pick_service_urlc                 C   sv   t jj|  d}d| |||i}tdddddd}| jj|||d}|jdkr6| j	r6t
d	|j| j|j|fS )
Nr   zf.reqz&boq_translate-webserver_20201207.13_p0r6   c)rpcidsblzsoc-appzsoc-platformz
soc-devicert)paramsdata   #Unexpected status code "{}" from {})r   TRANSLATE_RPCformatr:   r5   r4   r   poststatus_coderaise_Exception	Exceptionr!   r+   )r%   r+   r,   r-   urlrA   r@   rr(   r(   r)   
_translatek   s    
zTranslator._translatec           
      C   s   d}| j dkr| j|}tj| j |||||d}tjj|  d}| j	j
||d}|jdkr9t|j}	|	|fS | jrFtd|j| j|td d d< t|fS )	N webapp)r   queryr-   r,   tokenoverrider;   )r@   rB   rC   r   )r"   r#   dor   build_paramsr   	TRANSLATErE   r:   r   getrG   format_jsonr+   r$   rI   r!   r   )
r%   r+   r,   r-   rQ   rP   r@   rJ   rK   rA   r(   r(   r)   _translate_legacy   s"   

zTranslator._translate_legacyc                 C   sZ   ddddddddd	d
dd}i }|  D ]\}}|t|k r&|| r&|| nd ||< q|S )Ntranslationzall-translationszoriginal-languagezpossible-translations
confidencezpossible-mistakeslanguagesynonymsdefinitionsexampleszsee-also)r   r6                              )itemsr7   )r%   rA   response_parts_name_mappingextraindexcategoryr(   r(   r)   _parse_extra_data   s&   zTranslator._parse_extra_datar   autoc              
   C   s  |  ddd }|  ddd }|dkr2|tvr2|tv r%t| }n|tv r.t| }ntd|tvrL|tv r?t| }n|tv rHt| }ntd|}| |||\}}d}ddg}d}	|d	D ]Y}
|psd
t d
|
d d v }|swqdd}t|
D ]1\}}|d
kr|
t	d|d  dkr| }|s|dkr|d  d7  < q}|dkr|d  d7  < q}|	|
7 }	|d |d kr nqdt
|	}t
|d d }|d d d d }ttdd |d d d d }|rdndtdd |}|dkrz|d }W n   Y |dkrz|d d }W n   Y d }d }z|d d }W n   Y d }z|d d d d }W n   Y ||||d}t||||||||d}|S )N_r6   r   rm   invalid source languageinvalid destination languageFrM   
"   \[]r^      c                 S   s$   t | d t| dkr| d S g S )Nr   r^   r6   )r   r7   partr(   r(   r)   <lambda>   s   $ z&Translator.translate.<locals>.<lambda>r_    c                 S   s   | j S )N)r+   rx   r(   r(   r)   rz      s    )rY   partsorigin_pronunciationparsed)r-   r,   originr+   pronunciationr|   
extra_dataresponse)lowersplitr
   r   r	   
ValueErrorrL   r4   	enumeratemaxr2   loadslistmapjoinr   )r%   r+   r,   r-   r   rA   r   token_foundsquare_bracket_countsresplineis_in_stringrj   charr~   should_spacingtranslated_parts
translatedrY   r}   r   r   resultr(   r(   r)   	translate   s   




"

zTranslator.translatec              	   K   s  |  ddd }|  ddd }|dkr2|tvr2|tv r%t| }n|tv r.t| }ntd|tvrL|tv r?t| }n|tv rHt| }ntdt|trkg }|D ]}| j|f||d|}|	| qU|S |}| |||\}	}
d
d	d
 |	d D }| |	}z|	d }W n	 ty   Y nw |}z
|	d d d }W n	 ty   Y nw |du rz
|	d d d }W n   Y |tv r||kr|}t|||||||
d}|S )uS  Translate text from source language to destination language

        :param text: The source text(s) to be translated. Batch translation is supported via sequence input.
        :type text: UTF-8 :class:`str`; :class:`unicode`; string sequence (list, tuple, iterator, generator)

        :param dest: The language to translate the source text into.
                     The value should be one of the language codes listed in :const:`googletrans.LANGUAGES`
                     or one of the language names listed in :const:`googletrans.LANGCODES`.
        :param dest: :class:`str`; :class:`unicode`

        :param src: The language of the source text.
                    The value should be one of the language codes listed in :const:`googletrans.LANGUAGES`
                    or one of the language names listed in :const:`googletrans.LANGCODES`.
                    If a language is not specified,
                    the system will attempt to identify the source language automatically.
        :param src: :class:`str`; :class:`unicode`

        :rtype: Translated
        :rtype: :class:`list` (when a list is passed)

        Basic usage:
            >>> from googletrans import Translator
            >>> translator = Translator()
            >>> translator.translate('안녕하세요.')
            <Translated src=ko dest=en text=Good evening. pronunciation=Good evening.>
            >>> translator.translate('안녕하세요.', dest='ja')
            <Translated src=ko dest=ja text=こんにちは。 pronunciation=Kon'nichiwa.>
            >>> translator.translate('veritas lux mea', src='la')
            <Translated src=la dest=en text=The truth is my light pronunciation=The truth is my light>

        Advanced usage:
            >>> translations = translator.translate(['The quick brown fox', 'jumps over', 'the lazy dog'], dest='ko')
            >>> for translation in translations:
            ...    print(translation.origin, ' -> ', translation.text)
            The quick brown fox  ->  빠른 갈색 여우
            jumps over  ->  이상 점프
            the lazy dog  ->  게으른 개
        rn   r6   r   rm   ro   rp   )r,   r-   rM   c                 S   s    g | ]}|d  r|d  ndqS )r   rM   r(   ).0dr(   r(   r)   
<listcomp>N  s     z/Translator.translate_legacy.<locals>.<listcomp>r^   N)r-   r,   r   r+   r   r   r   )r   r   r
   r   r	   r   
isinstancer   translate_legacyappendr   rl   rI   EXCLUDESr   )r%   r+   r,   r-   kwargsr   itemr   r   rA   r   r   pronr(   r(   r)   r   	  s`   '





zTranslator.translate_legacyc                 C   s0   | j |ddd}t|j|jdd |jd}|S )Nrm   r   )r-   r,   rY   langrY   r   )r   r   r-   r   rU   	_response)r%   r+   r   r   r(   r(   r)   detectp  s   zTranslator.detectc           
      K   s   t |trg }|D ]}| |}|| q	|S | |dd|\}}d}d}	z*t|d d dkr>|d d }|d d }	nd|d d }|d d d }	W n	 tyY   Y nw t||	|d	}|S )
u1  Detect language of the input text

        :param text: The source text(s) whose language you want to identify.
                     Batch detection is supported via sequence input.
        :type text: UTF-8 :class:`str`; :class:`unicode`; string sequence (list, tuple, iterator, generator)

        :rtype: Detected
        :rtype: :class:`list` (when a list is passed)

        Basic usage:
            >>> from googletrans import Translator
            >>> translator = Translator()
            >>> translator.detect('이 문장은 한글로 쓰여졌습니다.')
            <Detected lang=ko confidence=0.27041003>
            >>> translator.detect('この文章は日本語で書かれました。')
            <Detected lang=ja confidence=0.64889508>
            >>> translator.detect('This sentence is written in English.')
            <Detected lang=en confidence=0.22348526>
            >>> translator.detect('Tiu frazo estas skribita en Esperanto.')
            <Detected lang=eo confidence=0.10538048>

        Advanced usage:
            >>> langs = translator.detect(['한국어', '日本語', 'English', 'le français'])
            >>> for lang in langs:
            ...    print(lang.lang, lang.confidence)
            ko 1
            ja 0.92929292
            en 0.96954316
            fr 0.043500196
        r   rm   rM   g        rb   r   r6   r   r   )	r   r   r   r   rW   r7   r   rI   r   )
r%   r+   r   r   r   r   rA   r   r-   rY   r(   r(   r)   detect_legacyu  s*   

zTranslator.detect_legacy)r   rm   )__name__
__module____qualname____doc__r   r   r   typingDictstrhttpcoreSyncHTTPTransportr   r*   r5   r:   rL   rW   rl   r   r   r   r   r(   r(   r(   r)   r      s,    
 

\gr   )r   r8   r   rer2   r   r   r   googletransr   r   googletrans.gtokenr   googletrans.constantsr   r   r   r	   r
   r   r   r   googletrans.modelsr   r   r   r   r4   r   r(   r(   r(   r)   <module>   s   (