
    Pi"4                         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ZddlZddl	m
Z
mZ ddlmZ ddlmZ  G d d          ZdS )zWrapper on espeak-ng library    N)TupleDict)	EspeakAPI)EspeakVoicec                   f   e Zd ZdZdZd Zed             Zed             Zd Z	de
fdZed	efd
            Zed             Zd Zedeeeef         fd            Zed             Zed             Zed             Z ej        d          dd            Zd Zd ZddededefdZdefdZdS )EspeakWrappera  Wrapper on espeak shared library

    The aim of this wrapper is not to be exhaustive but to encapsulate the
    espeak functions required for phonemization. It relies on a espeak shared
    library (*.so on Linux, *.dylib on Mac and *.dll on Windows) that must be
    installed on the system.

    Use the function `EspeakWrapper.set_library()` before instanciation to
    customize the library to use.

    Raises
    ------
    RuntimeError if the espeak shared library cannot be loaded

    Nc                     d | _         d | _        d | _        t          |                                           | _        d | _        d | _        d S N)_version
_data_path_voicer   library_espeak_libc_
_tempfile_selfs    u/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/phonemizer/backend/espeak/wrapper.py__init__zEspeakWrapper.__init__4   sF     *. !00     c                     | j         bt          j        dk    rt          j        j        n;t          j                            t          j        	                    d                    | _         | j         S )Nwin32c)
r   sysplatformctypeswindllmsvcrtcdllLoadLibraryutilfind_libraryr   s    r   _libczEspeakWrapper._libcB   sU    ;(+(?(?$$''(@(@(E(EFF K {r   c                     | j         <t          j                    | _         t          j        | j         | j         j                   | j         S r
   )r   tempfileNamedTemporaryFileweakreffinalizecloser   s    r   	_tempfilezEspeakWrapper._tempfileJ   s>    ?" '9;;DOT_do.CDDDr   c                 ,    | j         | j        | j        dS )z/For pickling, when phonemizing on multiple jobs)version	data_pathvoice)r   r   r   r   s    r   __getstate__zEspeakWrapper.__getstate__S   s"     }[" " 	"r   statec                 :   |                                   |d         | _        |d         | _        |d         | _        | j        rXd| j        j        v r)|                     | j        j        dd                    dS |                     | j        j                   dS dS )z1For unpickling, when phonemizing on multiple jobsr,   r-   r.   mb   N)r   r   r   r   
identifier	set_voicelanguage)r   r0   s     r   __setstate__zEspeakWrapper.__setstate__Z   s    i(,Gn; 	5t{---t{5abb9:::::t{344444		5 	5r   r   c                     || _         dS )a`  Sets the espeak backend to use `library`

        If this is not set, the backend uses the default espeak shared library
        from the system installation.

        Parameters
        ----------
        library (str or None) : the path to the espeak shared library to use as
          backend. Set `library` to None to restore the default.

        N)_ESPEAK_LIBRARYclsr   s     r   set_libraryzEspeakWrapper.set_libraryf   s     &r   c                    | j         r| j         S dt          j        v r~t          j        t          j        d                   }|                                rt          j        |t          j                  st          d| d          |	                                S t          j                            d          pt          j                            d          }|st          d          |S )a  Returns the espeak library used as backend

        The following precedence rule applies for library lookup:

        1. As specified by BaseEspeakBackend.set_library()
        2. Or as specified by the environment variable
           PHONEMIZER_ESPEAK_LIBRARY
        3. Or the default espeak library found on the system

        Raises
        ------
        RuntimeError if the espeak library cannot be found or if the
          environment variable PHONEMIZER_ESPEAK_LIBRARY is set to a
          non-readable file

        PHONEMIZER_ESPEAK_LIBRARYzPHONEMIZER_ESPEAK_LIBRARY=z is not a readable filez	espeak-ngespeakzfailed to find espeak library)r9   osenvironpathlibPathis_fileaccessR_OKRuntimeErrorresolver   r!   r"   r:   s     r   r   zEspeakWrapper.libraryu   s    $  	'&&&"*44l2:.I#JKKGOO%% /")GRW*E*E /". . . ./ / / ??$$$ ((55 3((22 	  	1/1 1 1r   c                    | j                                         \  }}t          j        |                                          | _        | j                                        st          d          |                                                                	                    d          d         
                    dd          }t          d |	                    d          D                       | _        dS )	z9Initializes version and dapa path from the espeak libraryz(failed to retrieve espeak data directory r   z-dev c              3   4   K   | ]}t          |          V  d S r
   )int).0vs     r   	<genexpr>z8EspeakWrapper._fetch_version_and_path.<locals>.<genexpr>   s(      AAc!ffAAAAAAr   .N)r   inforB   rC   decoder   is_dirrG   stripsplitreplacetupler   )r   r,   r-   s      r   _fetch_version_and_pathz%EspeakWrapper._fetch_version_and_path   s    !\..00 ",y'7'7'9'9::%%'' 	KIJJJ ..""((**0055a8@@LLAAgmmC.@.@AAAAAr   returnc                 F    | j         |                                  | j         S )z?The espeak version as a tuple of integers (major, minor, patch))r   rY   r   s    r   r,   zEspeakWrapper.version   s&     = ((***}r   c                     | j         j        S )z-The espeak library as a pathlib.Path instance)r   library_pathr   s    r   r]   zEspeakWrapper.library_path   s     |((r   c                 F    | j         |                                  | j         S )z4The espeak data directory as a pathlib.Path instance)r   rY   r   s    r   r-   zEspeakWrapper.data_path   s&     ?"((***r   c                     | j         S )zsThe configured voice as an EspeakVoice instance

        If `set_voice` has not been called, returns None

        )r   r   s    r   r.   zEspeakWrapper.voice   s     {r   )maxsizec           	         |r"t          |                                          }| j                            |pd          }d}g }||         r||         j        }|                    t          t          j        |j                  	                    dd          t          j        |j
                  dd         t          j        |j                                       |dz  }||         |S )z>Voices available for phonemization, as a list of `EspeakVoice`)r6   Nr   _rJ      )namer6   r4   )r   	to_ctypesr   list_voicescontentsappendr@   fsdecoderd   rW   	languagesr4   )r   rd   voicesindexavailable_voicesr.   s         r   rm   zEspeakWrapper.available_voices   s      	:---7799D))$,$77Um 	5M*E##K[,,44S#>>U_55abb9;u'788%: %: %: ; ; ; QJE Um 	  r   c                    d|v r d |                      d          D             }n1i }|                                  D ]}|j        |vr|j        ||j        <   	 ||         }n"# t          $ r t	          d| d          dw xY w| j                            |                    d                    dk    rt	          d	| d          |                                 }|st	          d	| d          || _	        dS )
a!  Setup the voice to use for phonemization

        Parameters
        ----------
        voice_code (str) : Must be a valid language code that is actually
          supported by espeak

        Raises
        ------
        RuntimeError if the required voice cannot be initialized

        r2   c                 8    i | ]}|j         d d         |j         S )r3   N)r4   )rN   r.   s     r   
<dictcomp>z+EspeakWrapper.set_voice.<locals>.<dictcomp>   s9     > > >  $e&6> > >r   mbrolazinvalid voice code ""Nutf8r   zfailed to load voice ")
rm   r6   r4   KeyErrorrG   r   set_voice_by_nameencode
_get_voicer   )r   
voice_code	availabler.   
voice_names        r   r5   zEspeakWrapper.set_voice   sU    :> >!228<<> > >II I..00 A A>22050@Ien-	O":.JJ 	O 	O 	OCjCCCDD$N	O <))**;*;F*C*CDDII66668 8 8 !! 	GE
EEEFFFs   A   A?c                 n    | j                                         }|j        rt          j        |          S dS )znReturns the current voice used for phonemization

        If no voice has been set up, returns None.

        N)r   get_current_voicerd   r   from_ctypes)r   r.   s     r   rw   zEspeakWrapper._get_voice  s7     ..00: 	2*5111tr   Ftexttiec                 :   | j         t          d          |r| j        dk    rt          d          t          j        t          j        |                    d                              }d}| j        dk    rd}n-|rdt          d	          d
z  z  }nt          d          d
z  dz  }g }|j        j	        Q| j
                            |||          }|r'|                    |                                           |j        j	        Qd                    |          S )u  Translates a text into phonemes, must call set_voice() first.

        This method is used by the Espeak backend. Wrapper on the
        espeak_TextToPhonemes function.

        Parameters
        ----------
        text (str) : the text to phonemize

        tie (bool, optional) : When True use a '͡' character between
          consecutive characters of a single phoneme. Else separate phoneme
          with '_'. This option requires espeak>=1.49. Default to False.

        Returns
        -------
        phonemes (str) : the phonemes for the text encoded in IPA, with '_' as
          phonemes separator (excepted if ``tie`` is True) and ' ' as word
          separator.

        Nno voice specified)rc   0   r3   z,tie option only compatible with espeak>=1.49rs   rc         u   ͡   rb      rJ   )r.   rG   r,   r   pointerc_char_prv   ordrg   valuer   text_to_phonemesrh   rS   join)r   r~   r   text_ptr	text_modephonemes_moderesultphonemess           r   r   zEspeakWrapper.text_to_phonemes  s3   * :3444 	@4<:-->@ @ @ >&/$++f2E2E"F"FGG 	
 <:%%,MM 	1,s4yyA~=MMHHMD0M%1|44)]4 4H 1hoo//000	 %1
 xxr   c                    | j         dk     rt          d          | j        t          d          t          j        t          j        g| j        j        _        t          j        | j        j        _	        t          j        g| j        j
        _        t          j        | j        j
        _	        | j                            d           | j                            | j        j                                        | j        j                                                  }| j                            dt'          d          dz  z  |           | j                            t          j        |                    d	                    t          j        t-          |          d
z             t          j        d
                    }| j        
                    |           |dk    rt          d          | j                            d           | j                                                                                                        }|S )a  Translates a text into phonemes, must call set_voice() first.

        Only compatible with espeak>=1.49. This method is used by the
        EspeakMbrola backend. Wrapper on the espeak_Synthesize function.

        Parameters
        ----------
        text (str) : the text to phonemize

        Returns
        -------
        phonemes (str) : the phonemes for the text encoded in SAMPA, with '_'
          as phonemes separator and no word separation.

        )rc   1   z not compatible with espeak<=1.48Nr   r      rb   r   rs   rc   zfailed to synthetize)r,   rG   r.   r   r   r#   fopenargtypesc_void_prestypefclosec_intr*   truncaterd   rv   moder   set_phoneme_tracer   
synthetizec_size_tlenc_uintseekreadrS   rU   )r   r~   file_pstatus
phonemizeds        r   r   zEspeakWrapper.synthetize@  s   " <'!!ABBB:3444 &,_fo$F
!#)?
 &,o%6
"$*L
! 	"""!!N&&((N&&((* * 	&&y3s88q='@&III((ODKK//00OCIIM**M$! ! 	
&!!!Q;;5666A^((**113399;;
r   r
   )F)__name__
__module____qualname____doc__r9   r   propertyr#   r*   r/   r   r7   classmethodstrr<   r   rY   r   rM   r,   r]   r-   r.   	functools	lru_cacherm   r5   rw   boolr   r    r   r   r   r      s        $ O     X   X" " "
5$ 
5 
5 
5 
5 &# & & & [& " " ["HB B B sC}-    X ) ) X)   X   X Y&&&      '& $( ( (T	 	 	2  2 S 2 t 2  2  2  2  2 h2s 2 2 2 2 2 2r   r   )r   r   ctypes.utilr   r@   rB   r   r%   r'   typingr   r   phonemizer.backend.espeak.apir   phonemizer.backend.espeak.voicer   r   r   r   r   <module>r      s    # "          				  



           3 3 3 3 3 3 7 7 7 7 7 7S S S S S S S S S Sr   