o
    i                  
   @   sx  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 ddlmZ ddlmZmZ ddlmZ zddlZddlm Z  W n  e!y Z" ze#de"  e#d e$de" dZ"["ww eej%&dZ'dZ(dZ)de*defddZ+dedefddZ,dede*fdd Z-eG d!d" d"eZ.G d#d$ d$eZ/dS )%z4Kokoro TTS service implementation using kokoro-onnx.    N)	dataclass)Path)AsyncGeneratorOptional)logger)	BaseModel)create_stream_resampler)
ErrorFrameFrameTTSAudioRawFrame)TTSSettings)
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                 C   s   t d|  d| d |jjddd tj| ddd}|  t|d}|jd	d
D ]}|	| q,W d   n1 s>w   Y  t d|  dS )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chunk r&   O/home/ubuntu/.local/lib/python3.10/site-packages/pipecat/services/kokoro/tts.py_download_file,   s   r(   
model_pathvoices_pathc                 C   s,   |   s	tt|  |  stt| dS dS )z)Download model files if they don't exist.N)existsr(   KOKORO_MODEL_URLKOKORO_VOICES_URL)r)   r*   r&   r&   r'   _ensure_model_files8   s
   
r.   languagereturnc                 C   sN   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
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   )r/   LANGUAGE_MAPr&   r&   r'   language_to_kokoro_language@   s   rD   c                   @   s   e Zd ZdZdS )KokoroTTSSettingszSettings for KokoroTTSService.N)__name__
__module____qualname____doc__r&   r&   r&   r'   rE   Z   s    rE   c                       s   e Zd ZU dZeZeed< G d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dZdefddZdede
fddZede
de
deedf fddZ  ZS )KokoroTTSServicezKokoro TTS service implementation.

    Provides local text-to-speech synthesis using kokoro-onnx.
    Automatically downloads model files on first use.
    	_settingsc                   @   s    e Zd ZU dZejZeed< dS )zKokoroTTSService.InputParamsa  Input parameters for Kokoro TTS configuration.

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

        Parameters:
            language: Language to use for synthesis.
        r/   N)rF   rG   rH   rI   r   r9   r/   __annotations__r&   r&   r&   r'   InputParamsk   s   
 	rM   N)voice_idr)   r*   paramssettingsrN   r)   r*   rO   rP   c          
         s   | j ddtjd}|dur| dd ||_|dur%| d |s%|j|_|dur.|| t jd
dd|d| |rAt	|nt
d }|rKt	|nt
d	 }	t||	 tt|t|	| _t | _dS )aA  Initialize the Kokoro TTS service.

        Args:
            voice_id: Voice identifier to use for synthesis.

                .. deprecated:: 0.0.105
                    Use ``settings=KokoroTTSService.Settings(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=KokoroTTSService.Settings(...)`` instead.

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

        N)modelvoicer/   rN   rR   rO   T)push_start_framepush_stop_framesrP   zkokoro-v1.0.onnxzvoices-v1.0.binr&   )Settingsr   r9   "_warn_init_param_moved_to_settingsrR   r/   apply_updatesuper__init__r   KOKORO_CACHE_DIRr.   r   str_kokoror   
_resampler)
selfrN   r)   r*   rO   rP   kwargsdefault_settings
model_filevoices	__class__r&   r'   rY   w   s4   


zKokoroTTSService.__init__r0   c                 C   s   dS )z;Indicate that this service supports TTFB and usage metrics.Tr&   )r^   r&   r&   r'   can_generate_metrics   s   z%KokoroTTSService.can_generate_metricsr/   c                 C   s   t |S )zConvert a Language enum to kokoro-onnx language format.

        Args:
            language: The language to convert.

        Returns:
            The kokoro-onnx language code.
        )rD   )r^   r/   r&   r&   r'   language_to_service_language   s   	z-KokoroTTSService.language_to_service_languagetext
context_idc           	   
   C  s   t |  d| d z{zK| |I dH  | jj|| jj| jjdd}|2 z/3 dH W \}}|  I dH  |d 	t
j }| j||| jI dH }t|| jd|dV  q&6 W n tys } ztd	| d
V  W Y d}~nd}~ww W |  I dH  dS W |  I dH  dS |  I dH  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      ?)rR   langspeedi     )audiosample_ratenum_channelsrh   zUnknown error occurred: )error)r   r   start_tts_usage_metricsr\   create_streamrK   rR   r/   stop_ttfb_metricsastypenpint16tobytesr]   resamplern   r   	Exceptionr	   )	r^   rg   rh   r   samplesrn   audio_int16
audio_dataer&   r&   r'   run_tts   s8   

"zKokoroTTSService.run_tts)rF   rG   rH   rI   rE   rU   rL   r   rM   r   r[   rY   boolre   r   rf   r   r   r
   r~   __classcell__r&   r&   rc   r'   rJ   a   s2   
 D(rJ   )0rI   osdataclassesr   pathlibr   typingr   r   numpyru   logurur   pydanticr   pipecat.audio.utilsr   pipecat.frames.framesr	   r
   r   pipecat.services.settingsr   pipecat.services.tts_servicer   pipecat.transcriptions.languager   r   (pipecat.utils.tracing.service_decoratorsr   r   kokoro_onnxr   ModuleNotFoundErrorr}   rp   ry   path
expanduserrZ   r,   r-   r[   r(   r.   rD   rE   rJ   r&   r&   r&   r'   <module>   sB   
