
    Nj4              "       T   U 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	 d dl
Z
d dlZd dlmZmZmZmZmZ d dlmZ d dlmZmZ d dl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& d dl'm(Z( d dl)m*Z*  ejV                  e,      Z- e
j\                  dd      Z/da0e%dz  e1d<    eddd      Z2e2jg                  eg dddgdg       e2ji                  de      d        Z5e2ji                  d      d        Z6d Z7de8d e9fd!Z:e2jw                  d"       ed#       ed       ed      fd$e8d%e8dz  d&edz  fd'       Z<e/j{                         	 	 	 	 	 	 dYd(ee8 e
j|                  d)*      f   d+ee? e
j|                  d,*      f   d-ee@ e
j|                  d.*      f   d/ee8dz   e
j|                  d0d1      f   d2ee8dz   e
j|                  d3*      f   d4ee@ e
j|                  d5*      f   fd6       ZAe/j{                         dddddee eeed7d8e!dfd$ee8 e
j|                  d9*      f   d:ee8dz   e
j|                  d;d1      f   d<ee@ e
j|                  d=d>d?*      f   d/ee8dz   e
j|                  d@d1      f   d2ee8dz   e
j|                  d3*      f   dAee? e
j|                  dB*      f   dCeeB e
j|                  dD*      f   dEeeB e
j|                  dF*      f   dGeeB e
j|                  dH*      f   dIee? e
j|                  dJ*      f   dKee8 e
j|                  dL*      f   dMee8 e
j|                  dN*      f   dOee? e
j|                  dP*      f   d4ee@ e
j|                  d5*      f   fdQ       ZCe/j{                         	 	 	 dZdRee8 e
j                  dS*      f   dTee8 e
j                  dU*      f   d<ee@ e
j|                  d=d>d?*      f   d/ee8dz   e
j|                  dVd1      f   d2ee8dz   e
j|                  d3*      f   f
dW       ZEe,dXk(  r e/        yy)[    N)Path)Queue)FastAPIFileFormHTTPException
UploadFile)CORSMiddleware)HTMLResponseStreamingResponse)	Annotated)stream_audio_chunks)DEFAULT_EOS_THRESHOLDDEFAULT_FRAMES_AFTER_EOSDEFAULT_LSD_DECODE_STEPSDEFAULT_NOISE_CLAMPDEFAULT_TEMPERATUREMAX_TOKEN_PER_CHUNKget_default_text_for_languageget_default_voice_for_language)TTSModelexport_model_state)enable_logging)_ORIGINS_OF_PREDEFINED_VOICESz2Kyutai Pocket TTS - Text-to-Speech generation toolF)helppretty_exceptions_show_locals	tts_modelzKyutai Pocket TTS APIzText-to-Speech generation APIz1.0.0)titledescriptionversion)zhttp://localhost:3000z&https://pod1-10007.internal.kyutai.orgzhttps://kyutai.orgT*)allow_originsallow_credentialsallow_methodsallow_headers/)response_classc                    K   t        t              j                  dz  dz  } | j                         }t	        t        t        j                               |j                  dt        t        t        j                                    }|S w)zServe the frontend.staticz
index.htmlDEFAULT_TEXT_PROMPT)
r   __file__parent	read_textprintstrr   originreplacer   )static_pathcontents     `/Users/ahmed/devFolder/Ultron/claude-voice/.venv/lib/python3.12/site-packages/pocket_tts/main.pyrootr5   >   sm      x.''(2\AK##%G	#i
 oo<SAQAQ=RSG Ns   BBz/healthc                     K   ddiS w)Nstatushealthy r9       r4   healthr;   K   s     i  s   c                      G d dt         j                        }t        j                  ||      }t	         ||       |t        j
                  j                  j                         y)z=Allows writing to the StreamingResponse as if it were a file.c                   $    e Zd Zd Zd Zd Zd Zy)'write_to_queue.<locals>.FileLikeToQueuec                     || _         y N)queue)selfrA   s     r4   __init__z0write_to_queue.<locals>.FileLikeToQueue.__init__T   s	    DJr:   c                 :    | j                   j                  |       y r@   rA   put)rB   datas     r4   writez-write_to_queue.<locals>.FileLikeToQueue.writeW       JJNN4 r:   c                      y r@   r9   rB   s    r4   flushz-write_to_queue.<locals>.FileLikeToQueue.flushZ   s    r:   c                 :    | j                   j                  d        y r@   rE   rK   s    r4   closez-write_to_queue.<locals>.FileLikeToQueue.close]   rI   r:   N)__name__
__module____qualname__rC   rH   rL   rN   r9   r:   r4   FileLikeToQueuer>   S   s    		!		!r:   rR   )model_statetext_to_generateN)ioIOBaser   generate_audio_streamr   configmimisample_rate)rA   rT   rS   rR   audio_chunkss        r4   write_to_queuer\   P   sT    !")) ! 222B 3 L .i>N>N>S>S>_>_`r:   rT   rS   c              #      K   t               }t        j                  t        || |f      }|j	                          d}	 |j                         }|n
|dz  }| |j                          y w)N)targetargsr      )r   	threadingThreadr\   startgetjoin)rT   rS   rA   threadirG   s         r4   generate_data_with_staterh   f   sn     GE ^5BRT_:`aF
LLN 	
A
yy{<	Q
  KKMs   A*A,z/tts.text	voice_url	voice_wavc                    | j                         st        dd      |$|"t        t        t        j
                              }||t        dd      |t|j                  d      s7|j                  d      s&|j                  d      s|t        v st        dd	      t        j                  |      }t        j                  d
|       n||j                  rt        |j                        j                  nd}t        j                  d|      5 }|j                   j#                         }|j%                  |       |j'                          |j(                  }ddd       	 t        j+                  t              d      }t-        j.                  |       nt        dd      t1        t3        | |      dddd      S # 1 sw Y   hxY w# t-        j.                         w xY w)aJ  
    Generate speech from text using the pre-loaded voice prompt or a custom voice.

    Args:
        text: Text to convert to speech
        voice_url: Optional built-in voice name (e.g., "alba"), or voice URL (http://, https://, or hf://)
        voice_wav: Optional uploaded voice file (mutually exclusive with voice_url)
    i  zText cannot be empty)status_codedetailNz+Cannot provide both voice_url and voice_wavzhttp://zhttps://zhf://z5voice_url must start with http://, https://, or hf://zUsing voice from URL: %sz.wavF)deletesuffixT)truncatei  zThis should never happen.z	audio/wavz)attachment; filename=generated_speech.wavchunked)zContent-DispositionzTransfer-Encoding)
media_typeheaders)stripr   r   r/   r   r0   
startswithr   "_cached_get_state_for_audio_promptloggingwarningfilenamer   rp   tempfileNamedTemporaryFilefilereadrH   rL   nameget_state_for_audio_promptosunlinkr   rh   )ri   rj   rk   rS   rp   	temp_filer3   temp_file_paths           r4   text_to_speechr   y   s    ::<4JKKY.23y7G7G3HI	!64abb   +##J/##G,99(_   BB9M2I>		4=4F4Fi(()00F((fEnn))+GOOG$OO&^^N	 F	&#>>tN?S^b>cKIIn%4OPP {3#N!*
  FE IIn%s   AG " G  G	G#hostzHost to bind to)r   portzPort to bind toreloadzEnable auto-reloadlanguagezLanguage for the TTS model. 'english_2026-01', 'english_2026-04', 'english', 'french_24l', 'german_24l', 'portuguese', 'italian', 'spanish'. Incompatible with the config argument. Default is 'english', which is the same model as 'english_2026-04'.)r   show_defaultrX   zPath to locally-saved model config .yaml file. Incompatible with the language argument. If not provided, will use the default English model.quantizez.Apply int8 quantization to reduce memory usagec                 f    t        j                  |||      at        j                  d| ||       y)zStart the FastAPI server.)r   rX   r   zpocket_tts.main:web_app)r   r   r   N)r   
load_modelr   uvicornrun)r   r   r   r   rX   r   s         r4   server      s+    8 ##XfxXIKK)4Or:   z./tts_output.wavcpuzText to generatevoicezPath to audio conditioning file (voice to clone). Defaults to a built-in voice chosen from the language: 'giovanni' for italian, 'lola' for spanish, 'juergen' for german, 'rafael' for portuguese, 'estelle' for french, 'alba' otherwise.quietz-qz--quietzDisable logging outputa  Language for the TTS model. 'english_2026-01', 'english_2026-04', 'english', 'french_24l', 'spanish_24l','german_24l', 'portuguese_24l', 'italian_24l'. Incompatible with the config argument. Default is 'english', which is the same model as 'english_2026-04'. The '24l' variants are bigger models, not distilled yet and here only as preview. They're not the final models for those languages.lsd_decode_stepszNumber of generation stepstemperaturezTemperature for generationnoise_clampzNoise clamp valueeos_thresholdzEOS thresholdframes_after_eosz&Number of frames to generate after EOSoutput_pathzOutput path for generated audiodevicezDevice to use
max_tokensz#Maximum number of tokens per chunk.c           
      *   |rt         j                  nt         j                  }t        d|      5  | t	        |      } | dk(  rt
        j                  j                         } | j                         s+t        j                  d       t        j                  d      t        j                  |||||||      }|j                  |       |t!        |      }|j#                  |      }|j%                  || |	|      }t'        |
||j(                  j*                  j,                         |
dk7  rt        j/                  d	|
       t        j/                  d
       t        j/                  d       t        j/                  d       ddd       y# 1 sw Y   yxY w)z(Generate speech using Kyutai Pocket TTS.
pocket_ttsN-zNo input received from stdin.r`   )code)r   rX   tempr   r   r   r   )rS   rT   r   r   zResults written in %sz--------------------zPIf you want to try multiple voices and prompts quickly, try the `serve` command.zRIf you like Kyutai projects, comment, like, subscribe at https://x.com/kyutai_labs)rx   ERRORINFOr   r   sysstdinr~   ru   loggererrortyperExitr   r   tor   r   rW   r   rX   rY   rZ   info)ri   r   r   r   rX   r   r   r   r   r   r   r   r   r   	log_levelr   model_state_for_voicer[   s                     r4   generater      sQ   z "'GLLI	i	0<0:D3;99>>#Dzz|LL89**!$$''-#'
	 	V=28<E ) D DU K 66-!-!	 7 
 	Ky7G7G7L7L7X7XY #KK/=H^	
 	`	
S 
1	0	0s   EF		F
audio_pathz-Audio file or directory to convert and exportexport_pathzOutput file or directoryaT  Language for the TTS model. 'english_2026-01', 'english_2026-04', 'english', 'french_24l', 'german_24l','spanish_24l', 'portuguese_24l', 'italian_24l'. Incompatible with the config argument. Default is 'english', which is the same model as 'english_2026-04'. The '24l' variants are bigger models, not distilled yet and here only as preview.c                     |rt         j                  nt         j                  }t        d|      5  t	        j
                  ||      }|j                  | d      }t        ||       ddd       y# 1 sw Y   yxY w)z+Convert and save audio to .safetensors filer   )r   rX   T)audio_conditioningrq   N)rx   r   r   r   r   r   r   r   )r   r   r   r   rX   r   r   rS   s           r4   export_voicer   O  sc    > "'GLLI	i	0''&I	::)D ; 
 	;4 
1	0	0s   7A//A8__main__)	localhosti@  FNNF)FNN)FrU   rx   r   r   r{   ra   pathlibr   rA   r   r   r   fastapir   r   r   r   r	   fastapi.middleware.corsr
   fastapi.responsesr   r   typing_extensionsr   pocket_tts.data.audior   pocket_tts.default_parametersr   r   r   r   r   r   r   r   pocket_tts.models.tts_modelr   r   pocket_tts.utils.logging_utilsr   pocket_tts.utils.utilsr   	getLoggerrO   r   Typercli_appr   __annotations__web_appadd_middlewarerd   r5   r;   r\   r/   dictrh   postr   commandOptionintboolr   floatr   Argumentr   r9   r:   r4   <module>r      s   	  	 
       B B 2 = ' 5	 	 	 E 9 @			8	$
%++	=]b "	8d? !

!/NX_   
 %%  
 	S.	 /	 	Y! !a,s  & 	fS	 J#':;
;Tz; D ; ;| 	ALAEGL 	 	 	-P
C+<==
>P
C+<==
>P dLELL.BCCDP d
z 		
		P d
l	
	P( lell PQQ)P PJ 	BF 	[` 	 	 	! 	L_J_ 	! 	AF 	 	sh

C+=>>
?h
d
S
 	
		h
 T<5<<i>VWWXh
 d
. 	
	h
< d
l	
	=h
J  \U\\;<<Kh
P |u||!=>>Qh
V 5,%,,4G"HHIWh
X ULELLo$FFGYh
Z  \U\\GHH[h
` \U\\@AAah
f c<5<<_==>gh
h \U\\DEEih
n lell PQQoh
 h
` 	 \a 	 	5$5^U^^!PQQ$5 34N OOP	$5
 T<5<<i>VWWX$5 d
> 
	
	$5( d
l	
	)$5 $5N zI r:   