
    qiC                        d Z ddlZddlmZ ddlmZ ddlmZmZ ddl	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 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Zddl m!Z!  eejL                  jO                  d            Z(dZ)dZ*de+defdZ,dedefdZ-dede+fdZ.e G d de             Z/ G d  d!e      Z0y# e"$ r7Z# ejH                  de#         ejH                  d        e%de#       dZ#[#ww xY w)"z4Kokoro TTS service implementation using kokoro-onnx.    N)	dataclass)Path)AsyncGeneratorOptional)logger)	BaseModel)create_stream_resampler)
ErrorFrameFrameTTSAudioRawFrame)TTSSettings_warn_deprecated_param)
TTSService)Languageresolve_language)
traced_tts)KokorozException: zEIn order to use Kokoro, you need to `pip install pipecat-ai[kokoro]`.zMissing module: z~/.cache/kokoro-onnxz_https://github.com/thewh1teagle/kokoro-onnx/releases/download/model-files-v1.0/kokoro-v1.0.onnxz^https://github.com/thewh1teagle/kokoro-onnx/releases/download/model-files-v1.0/voices-v1.0.binurldestc                    t        j                  d|  d| d       |j                  j                  dd       t	        j
                  | dd      }|j                          t        |d      5 }|j                  d	
      D ]  }|j                  |        	 ddd       t        j                  d|        y# 1 sw Y   "xY w)z1Download a file from a URL to a destination path.zDownloading z to z...T)parentsexist_oki,  )streamtimeoutwbi    )
chunk_sizeNzDownloaded )
r   debugparentmkdirrequestsgetraise_for_statusopeniter_contentwrite)r   r   respfchunks        M/opt/pipecat/venv/lib/python3.12/site-packages/pipecat/services/kokoro/tts.py_download_filer*   ,   s    
LL<uDc23KKdT2<<D#6D	dD	 Q&&$&7 	EGGEN	 LL;tf%& s   .)B99C
model_pathvoices_pathc                     | j                         st        t        |        |j                         st        t        |       yy)z)Download model files if they don't exist.N)existsr*   KOKORO_MODEL_URLKOKORO_VOICES_URL)r+   r,   s     r)   _ensure_model_filesr1   8   s5    '4(+6      languagereturnc                 b   t         j                  dt         j                  dt         j                  dt         j                  dt         j
                  dt         j                  dt         j                  dt         j                  dt         j                  dt         j                  d	i
}t        | |d
      S )zConvert a Language enum to kokoro-onnx language code.

    Args:
        language: The Language enum value to convert.

    Returns:
        The corresponding kokoro-onnx locale code.

    zen-uszen-gbesfrhiitjaptzhT)use_base_code)r   ENEN_USEN_GBESFRHIITJAPTZHr   )r3   LANGUAGE_MAPs     r)   language_to_kokoro_languagerI   @   sv     	WTTTTTTTL Hl$GGr2   c                       e Zd ZdZy)KokoroTTSSettingszSettings for KokoroTTSService.N)__name__
__module____qualname____doc__ r2   r)   rK   rK   Z   s    (r2   rK   c                        e Zd ZU dZeZeed<    G d de      Zddddddde	e
   de	e
   d	e	e
   d
e	e   de	e   f
 fdZdefdZdede
fdZede
de
deedf   fd       Z xZS )KokoroTTSServicezKokoro TTS service implementation.

    Provides local text-to-speech synthesis using kokoro-onnx.
    Automatically downloads model files on first use.
    	_settingsc                   4    e Zd ZU dZej
                  Zeed<   y)KokoroTTSService.InputParamszInput parameters for Kokoro TTS configuration.

        .. deprecated:: 0.0.105
            Use ``KokoroTTSSettings`` directly via the ``settings`` parameter instead.

        Parameters:
            language: Language to use for synthesis.
        r3   N)rL   rM   rN   rO   r   r>   r3   __annotations__rP   r2   r)   InputParamsrU   k   s    	 &[[((r2   rW   N)voice_idr+   r,   paramssettingsrX   r+   r,   rY   rZ   c                    t        ddt        t        j                              }|t	        dt         d       ||_        |,t	        dt                |st        |j                        |_        ||j                  |       t        
| $  d
dd|d| |rt        |      nt        dz  }|rt        |      nt        d	z  }	t        ||	       t        t        |      t        |	            | _        t!               | _        y)a1  Initialize the Kokoro TTS service.

        Args:
            voice_id: Voice identifier to use for synthesis.

                .. deprecated:: 0.0.105
                    Use ``settings=KokoroTTSSettings(voice=...)`` instead.

            model_path: Path to the kokoro ONNX model file. Defaults to auto-downloaded file.
            voices_path: Path to the voices binary file. Defaults to auto-downloaded file.
            params: Configuration parameters for synthesis.

                .. deprecated:: 0.0.105
                    Use ``settings=KokoroTTSSettings(...)`` instead.

            settings: Runtime-updatable settings. When provided alongside deprecated
                parameters, ``settings`` values take precedence.
            **kwargs: Additional arguments passed to parent `TTSService`.

        N)modelvoicer3   rX   r]   rY   T)push_start_framepush_stop_framesrZ   zkokoro-v1.0.onnxzvoices-v1.0.binrP   )rK   rI   r   r>   r   r]   r3   apply_updatesuper__init__r   KOKORO_CACHE_DIRr1   r   str_kokoror	   
_resampler)selfrX   r+   r,   rY   rZ   kwargsdefault_settings
model_filevoices	__class__s             r)   rb   zKokoroTTSService.__init__w   s    > -0=
 ":/@'J%-" "8->?,G,X ) ))(3 	
!!%	
 		
 *4T*%9IL^9^
&1k"7GJ[7[J/c*os6{;13r2   r4   c                      y)z;Indicate that this service supports TTFB and usage metrics.TrP   )rg   s    r)   can_generate_metricsz%KokoroTTSService.can_generate_metrics   s    r2   r3   c                     t        |      S )zConvert a Language enum to kokoro-onnx language format.

        Args:
            language: The language to convert.

        Returns:
            The kokoro-onnx language code.
        )rI   )rg   r3   s     r)   language_to_service_languagez-KokoroTTSService.language_to_service_language   s     +844r2   text
context_idc                  K   t        j                  |  d| d       	 | j                  |       d{    | j                  j	                  || j
                  j                  | j
                  j                  d      }|2 3 d{   \  }}| j                          d{    |dz  j                  t        j                        j                         }| j                  j                  ||| j                         d{   }t!        || j                  d|       7 7 7 7 '6 n(# t"        $ r}t%        d	| 
       Y d}~nd}~ww xY w| j                          d{  7   y# | j                          d{  7   w xY ww)zSynthesize speech from text using kokoro-onnx.

        Uses the async streaming API to generate audio frames.

        Args:
            text: The text to synthesize.
            context_id: Unique identifier for this TTS context.

        z: Generating TTS []Ng      ?)r]   langspeedi     )audiosample_ratenum_channelsrr   zUnknown error occurred: )error)r   r   start_tts_usage_metricsre   create_streamrS   r]   r3   stop_ttfb_metricsastypenpint16tobytesrf   resamplery   r   	Exceptionr
   )	rg   rq   rr   r   samplesry   audio_int16
audio_dataes	            r)   run_ttszKokoroTTSService.run_tts   sm     	v/vQ78	+..t444\\//DNN00t~~7N7NVY 0 F /5  *g{,,...&66rxx@HHJ#'??#;#;d.>.>$ 
 '$ $ 0 0!")	  5.	 /5  	C%=aS#ABBB	C ((***$((***s   FD+ D!AD+ D)D#D)	D+  D%!AD+ ?D' "D+ #D)%D+ 'D+ )D+ *E- +	E4EE- EE- F&E)'F-FFFF)rL   rM   rN   rO   rK   SettingsrV   r   rW   r   rd   rb   boolrn   r   rp   r   r   r   r   __classcell__)rl   s   @r)   rR   rR   a   s     !H  
)i 
) #'$(%)(,04B4 3-B4 SM	B4
 c]B4 %B4 ,-B4Hd 	5X 	5# 	5 $+# $+3 $+>%QU+;V $+ $+r2   rR   )1rO   osdataclassesr   pathlibr   typingr   r   numpyr   logurur   pydanticr   pipecat.audio.utilsr	   pipecat.frames.framesr
   r   r   pipecat.services.settingsr   r   pipecat.services.tts_servicer   pipecat.transcriptions.languager   r   (pipecat.utils.tracing.service_decoratorsr   r    kokoro_onnxr   ModuleNotFoundErrorr   r{   r   path
expanduserrc   r/   r0   rd   r*   r1   rI   rK   rR   rP   r2   r)   <module>r      s    ; 	 !  +    7 
 J 3 F ?," **+ABC t d 
	' 	'4 	'7D 7t 7H( Hs H4 	 	 	N+z N+C  ,FLL;qc"#FLLXY
&qc*
++,s   
B; ;C7 2C22C7