o
    PhyP                     @   s  d Z ddlmZ ddlmZ ddlmZ ddlmZ ddl	m
Z
mZmZmZ ddlmZ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 dd
lmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z& ddl'm(Z( ddl)m*Z* ddl+m,Z, ddl-m.Z. G dd dZ/dS )u.   
translatepy v2.3

© Anime no Sekai — 2021
    )
ThreadPool)Thread)Union)BeautifulSoup)NavigableStringPageElementPreformattedStringTag)NoResultParameterTypeErrorParameterValueError)Language)DictionaryResultExampleResultLanguageResultSpellcheckResultTextToSpechResultTranslationResultTransliterationResult)
BaseTranslatorBingTranslateDeeplTranslateGoogleTranslateLibreTranslateMyMemoryTranslateReversoTranslateTranslateComTranslateYandexTranslateMicrosoftTranslate)List)Queue)Request)remove_spacesc                   @   s\  e Zd ZdZeeeeee	e
eeg	e dfdee dededdfdd	Zd
ededefddZd-dedededefddZd.deeeeef dededededeeeeef fddZd/dedededefddZd-dededefddZ dede!fd d!Z"d-dededede#fd"d#Z$d-dedede%fd$d%Z&d0ded'ed(edede'f
d)d*Z(d1d+d,Z)dS )2	Translatez.
    A class which groups all of the APIs
    Fservices_listrequestfastreturnNc                 C   s   t |tstdt|j|std|| _t |tr"| | _n|| _g | _	|D ]}t |t
s>t|t
s>tdj|d| j	| q*dS )a  
        A special Translator class grouping multiple translators to have better results.

        Parameters:
        ----------
            services_list : list
                A list of instanciated or not BaseTranslator subclasses to use as translators
            request : Request
                The Request class used to make requests
            fast : bool
                Enabling fast mode (concurrent processing) or not
        z6Parameter 'services_list' must be a list, {} was givenz+Parameter 'services_list' must not be emptyz;{service} must be a child class of the BaseTranslator classserviceN)
isinstancer   r   formattype__name__r   	FAST_MODEr%   servicesr   
issubclassappend)selfr$   r%   r&   r)    r3   P/var/www/html/env_mimamsha/lib/python3.10/site-packages/translatepy/translate.py__init__#   s   




zTranslate.__init__r)   indexc                 C   s8   t |tsd|jjjv r|| jd}n| }|||< |S )Nr%   )r%   )r*   r   r5   __code__co_varnamesr%   )r2   r)   r$   r6   r3   r3   r4   _instantiate_translatorT   s   
z!Translate._instantiate_translatorautotextdestination_languagesource_languagec              	         t |t |dtdtffdd dtdtdtf fdd}jrWt }g }tjD ]\}}t||||fd}	|	  |	|	 q0|j
|d	}
|
d
u rUtd|
S tjD ]\}}z	 ||dW   S  tyr   Y q\w td)u   
        Translates the given text to the given language

        i.e Good morning (en) --> おはようございます (ja)
        
translatorr6   c                    @    | j|} | j d}|d u rtdj|  d|S N)r;   r<   r=   "{service} did not return any valuer(   )r9   r/   	translater
   r+   __repr__r?   r6   result	dest_langr2   source_langr;   r3   r4   
_translatef      z'Translate.translate.<locals>._translatequeuec                    .   z|   ||d W d S  ty   Y d S w Nr?   r6   put	ExceptionrL   r?   r6   )rJ   r3   r4   _fast_translateo   
   z,Translate.translate.<locals>._fast_translatetargetargsthreadsN&No service has returned a valid resultrO   r   r   intr    r.   	enumerater/   r   startr1   getr
   rR   )r2   r;   r<   r=   rT   _queuerZ   r6   r)   threadrF   r3   )rJ   rH   r2   rI   r;   r4   rC   ]   ,   	zTranslate.translatehtml.parserd   htmlparserthreads_limitc           
         s   t | t |dtf fdd}t|tttfs%tt|t|}n|}dd |jdddD }tt	|}	|	
|| W d   n1 sJw   Y  t|tttfrY|S t|S )	uA  
        Translates the given HTML string or BeautifulSoup object to the given language

        i.e
         English: `<div class="hello"><h1>Hello</h1> everyone and <a href="/welcome">welcome</a> to <span class="w-full">my website</span></div>`
         French: `<div class="hello"><h1>Bonjour</h1>tout le monde et<a href="/welcome">Bienvenue</a>à<span class="w-full">Mon site internet</span></div>`

        Note: This method is not perfect since it is not tag/context aware. Example: `<span>Hello <strong>everyone</strong></span>` will not be understood as
        "Hello everyone" with "everyone" in bold but rather "Hello" and "everyone" separately.

        Warning: If you give a `bs4.BeautifulSoup`, `bs4.element.PageElement` or `bs4.element.Tag` input (which are mutable), they will be modified.
        If you don't want this behavior, please make sure to pass the string version of the element:
        >>> result = Translate().translate_html(str(page_element), "French")

        Parameters:
        ----------
            html : str | bs4.element.PageElement | bs4.element.Tag | bs4.BeautifulSoup
                The HTML string to be translated. This can also be an instance of BeautifulSoup's `BeautifulSoup` element, `PageElement` or `Tag` element.
            destination_language : str
                The language the HTML string needs to be translated in.
            source_language : str, default = "auto"
                The language of the HTML string.
            parser : str, default = "html.parser"
                The parser that BeautifulSoup will use to parse the HTML string.
            threads_limit : int, default = 100
                The maximum number of threads that will be spawned by translate_html

        Returns:
        --------
            BeautifulSoup:
                The result will be the same element as the input `html` parameter with the values modified if the given
                input is of bs4.BeautifulSoup, bs4.element.PageElement or bs4.element.Tag instance.
            str:
                The result will be a string in any other case.

        nodec                    s8   z|  jt|  dj W d S  ty   Y d S w )N)r<   r=   )replace_withrC   strrF   rR   )ri   rH   r2   rI   r3   r4   rJ      s
   "z,Translate.translate_html.<locals>._translatec                 S   s&   g | ]}t |tst|d kr|qS ) )r*   r   r"   ).0tagr3   r3   r4   
<listcomp>   s   & z,Translate.translate_html.<locals>.<listcomp>T)r;   	recursiveN)r   r   r*   r   r	   r   rk   find_allr   r]   map)
r2   rf   r<   r=   rg   rh   rJ   pagenodespoolr3   rl   r4   translate_html   s   %zTranslate.translate_htmlenc              	      r>   )uT   
        Transliterates the given text

        i.e おはよう --> Ohayou
        r?   r6   c                    r@   rA   )r9   r/   transliterater
   r+   rD   rE   rG   r3   r4   _transliterate   rK   z/Translate.transliterate.<locals>._transliteraterL   c                    rM   rN   rP   rS   )rz   r3   r4   _fast_transliterate   rU   z4Translate.transliterate.<locals>._fast_transliteraterV   rY   Nr[   rO   r\   )r2   r;   r<   r=   r{   ra   rZ   r6   r)   rb   rF   r3   )rz   rH   r2   rI   r;   r4   ry      rc   zTranslate.transliteratec           
   	      s   t |dtdtffdd dtdtdtf fdd}jrRt }g }tjD ]\}}t||||fd}|  |	| q+|j
|d	}	|	d
u rPtd|	S tjD ]\}}z	 ||dW   S  tym   Y qWw td)z_
        Checks the spelling of a given text

        i.e God morning --> Good morning
        r?   r6   c                    s>     |  j|} | jd}|d u rtdj|  d|S )N)r;   r=   rB   r(   )r9   r/   
spellcheckr
   r+   rD   rE   )r2   rI   r;   r3   r4   _spellcheck   s   z)Translate.spellcheck.<locals>._spellcheckrL   c                    rM   rN   rP   rS   )r}   r3   r4   _fast_spellcheck   rU   z.Translate.spellcheck.<locals>._fast_spellcheckrV   rY   Nr[   rO   r\   )
r2   r;   r=   r~   ra   rZ   r6   r)   rb   rF   r3   )r}   r2   rI   r;   r4   r|      s*   	zTranslate.spellcheckc           	   	      s   dt dtffdd dtdt dtf fdd}jrMt }g }tjD ]\}}t||||fd}|  || q&|j	|d	}|d
u rKt
d|S tjD ]\}}z	 ||dW   S  tyh   Y qRw t
d)uz   
        Returns the language of the given text

        i.e 皆さんおはようございます！ --> Japanese
        r?   r6   c                    s<     |  j|} | jd}|d u rtdj|  d|S )N)r;   rB   r(   )r9   r/   languager
   r+   rD   rE   )r2   r;   r3   r4   	_language  s   z%Translate.language.<locals>._languagerL   c                    rM   rN   rP   rS   )r   r3   r4   _fast_language'  rU   z*Translate.language.<locals>._fast_languagerV   rY   Nr[   rO   )r   r]   r    r.   r^   r/   r   r_   r1   r`   r
   rR   )	r2   r;   r   ra   rZ   r6   r)   rb   rF   r3   )r   r2   r;   r4   r     s(   	zTranslate.languagec              	      r>   )z
        Returns a set of examples / use cases for the given word

        i.e Hello --> ['Hello friends how are you?', 'Hello im back again.']
        r?   r6   c                    r@   rA   )r9   r/   exampler
   r+   rD   rE   rG   r3   r4   _exampleJ  rK   z#Translate.example.<locals>._examplerL   c                    rM   rN   rP   rS   )r   r3   r4   _fast_exampleS  rU   z(Translate.example.<locals>._fast_examplerV   rY   Nr[   rO   r\   )r2   r;   r<   r=   r   ra   rZ   r6   r)   rb   rF   r3   )r   rH   r2   rI   r;   r4   r   A  rc   zTranslate.examplec              	      r>   )u`  
        Returns a list of translations that are classified between two categories: featured and less common

        i.e Hello --> {'featured': ['ハロー', 'こんにちは'], 'less_common': ['hello', '今日は', 'どうも', 'こんにちわ', 'こにちは', 'ほいほい', 'おーい', 'アンニョンハセヨ', 'アニョハセヨ'}
        r?   r6   c                    r@   rA   )r9   r/   
dictionaryr
   r+   rD   rE   rG   r3   r4   _dictionaryv  rK   z)Translate.dictionary.<locals>._dictionaryrL   c                    rM   rN   rP   rS   )r   r3   r4   _fast_dictionary  rU   z.Translate.dictionary.<locals>._fast_dictionaryrV   rY   Nr[   rO   r\   )r2   r;   r<   r=   r   ra   rZ   r6   r)   rb   rF   r3   )r   rH   r2   rI   r;   r4   r   m  rc   zTranslate.dictionaryfemalespeedgenderc              	      s   t |dtdtffdd dtdtdtf fdd}jrTt }g }tjD ]\}}	t|||	|fd}
|
  |	|
 q-|j
|d	}|d
u rRtd|S tjD ]\}}	z	 |	|dW   S  tyo   Y qYw td)a\  
        Gives back the text to speech result for the given text

        Args:
          text: the given text
          source_language: the source language

        Returns:
            the mp3 file as bytes

        Example:
            >>> from translatepy import Translator
            >>> t = Translator()
            >>> result = t.text_to_speech("Hello, how are you?")
            >>> with open("output.mp3", "wb") as output: # open a binary (b) file to write (w)
            ...     output.write(result.result)
                    # or:
                    result.write_to_file(output)
            # Or you can just use write_to_file method:
            >>> result.write_to_file("output.mp3")
            >>> print("Output of Text to Speech is available in output.mp3!")

            # the result is an MP3 file with the text to speech output
        r?   r6   c                    sB    | j|} | j d}|d u rtdj|  d|S )N)r;   r   r   r=   rB   r(   )r9   r/   text_to_speechr
   r+   rD   rE   )r   r2   rI   r   r;   r3   r4   _text_to_speech  s   z1Translate.text_to_speech.<locals>._text_to_speechrL   c                    rM   rN   rP   rS   )r   r3   r4   _fast_text_to_speech  rU   z6Translate.text_to_speech.<locals>._fast_text_to_speechrV   rY   Nr[   rO   r\   )r2   r;   r   r   r=   r   ra   rZ   r6   r)   rb   rF   r3   )r   r   r2   rI   r   r;   r4   r     s*   	zTranslate.text_to_speechc                 C   s   | j D ]}|  qdS )zB
        Cleans caches

        Returns:
            None
        N)r/   clean_cache)r2   r)   r3   r3   r4   r     s   

zTranslate.clean_cache)r:   )r:   rd   re   )rx   r:   )re   r   r:   )r'   N)*r-   
__module____qualname____doc__r   r   r   r   r   r   r   r   r   r!   r   r   boolr5   listr]   r9   rk   r   rC   r   r   r	   r   rw   r   ry   r   r|   r   r   r   r   r   r   r   r   r   r3   r3   r3   r4   r#      sB    
1	<,8,+), ,>r#   N)0r   multiprocessing.poolr   	threadingr   typingr   bs4r   bs4.elementr   r   r   r	   translatepy.exceptionsr
   r   r   translatepy.languager   translatepy.modelsr   r   r   r   r   r   r   translatepy.translatorsr   r   r   r   r   r   r   r   r   r   translatepy.utils.annotationsr   translatepy.utils.queuer    translatepy.utils.requestr!   translatepy.utils.sanitizer"   r#   r3   r3   r3   r4   <module>   s    $0