o
    ±ƒðjî/  ã                   @   sÀ   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mZ ddl	m
Z
mZmZ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mZ e ¡ Zddd„Zedkr^eƒ  dS dS )z)Flask web server with HTTP API for Piper.é    N)ÚPath)ÚAnyÚDictÚListÚOptional)Úurlopen)ÚFlaskÚrender_templateÚrequesté   )Ú
PiperVoiceÚSynthesisConfig)ÚVOICES_JSONÚdownload_voiceÚreturnc                     sÔ  t  ¡ } | jdddd� | jdtddd� | jd	d
ddd� | jddtdd� | jddtdd� | jddtdd� | jddddtdd� | jdddd � | jd!d"td#d$d� | jd%d&d'tt ¡ ƒgd(d)� | jd*d+d,d-� | jd.dd/d � |  ¡ ‰ t	j
ˆ jr�t	jnt	jd0� t ˆ ¡ ˆ js”ˆ jd1 ˆ _tˆ jƒ‰tˆ jƒ‰ˆ ¡ sÂˆ j}ˆ jD ]}t|ƒ|› d2� }t d3|¡ | ¡ rÁ|‰ nq¨ˆ ¡ sÎtd4ˆ› d5�ƒ‚ˆj d2¡‰tjˆˆ jdd6�‰ˆˆi‰ttd7d8d9�}i ‰|jd:d;gd<�d=tfd>d?„ƒ}|jd@d;gd<�d=tttf f‡‡‡fdAdB„ƒ}|jdCd;gd<�d=tttf f‡ ‡fdDdE„ƒ}|jdFd;gd<�d=tttf fdGdH„ƒ}|jdIdJgd<�d=tf‡fdKdL„ƒ}	|jdMdJgd<�d=tf‡ ‡‡‡‡fdNdO„ƒ}
|jˆ j ˆ j!dP� dQS )RzRun HTTP server.z--hostz0.0.0.0zHTTP server host)ÚdefaultÚhelpz--portiˆ  zHTTP server port)Útyper   r   z-mz--modelTzPath to Onnx model file)Úrequiredr   z-sz	--speakerzId of speaker (default: 0))r   r   z--length-scalez--length_scalezPhoneme lengthz--noise-scalez--noise_scalezGenerator noisez--noise-w-scalez--noise_w_scalez	--noise-wz	--noise_wzPhoneme width noisez--cudaÚ
store_truezUse GPU)Úactionr   z--sentence-silencez--sentence_silenceg        z&Seconds of silence after each sentencez
--data-dirz
--data_dirÚappendzJData directory to check for downloaded models (default: current directory))r   r   r   z--download-dirz--download_dirz1Path to download voices (default: first data dir))r   z--debugzPrint DEBUG messages to console)Úlevelr   ú.onnxzChecking '%s'zUnable to find voice: z (use piper.download_voices))Úuse_cudaÚinclude_alignmentsÚimgz/img)Ústatic_folderÚstatic_url_pathú/ÚGET)Úmethodsr   c                   S   s   t dƒS )z,Web page for testing a voice in the browser.z
index.html)r	   © r"   r"   ú“/tmp/claude-1000/-var-www-html-academy/3f42efd1-c2b7-4d08-9b05-30d86bb35479/scratchpad/piper/venv/lib/python3.10/site-packages/piper/http_server.pyÚ	app_indexq   s   zmain.<locals>.app_indexz/infoc                      s   ˆ ˆj jˆj jdœˆpddœS )a¯  Info about the current voice and most recently synthesized utterance.

        Outputs a JSON object with the format:
        {
          "voice": {
            "name": "<voice name>",
            "language": "<espeak voice/alphabet>",
            "num_speakers": <number of speakers>
          },
          "last": {                            (null until something is synthesized)
            "text": "<synthesized text>",
            "synthesize_seconds": <wall-clock synthesis time>,
            "phonemes": ["<phoneme>", ...],
            "alignments": [
              { "phoneme": "<phoneme>", "seconds": <duration> },
              ...
            ]
          }
        }
        )ÚnameÚlanguageÚnum_speakersN)ÚvoiceÚlast)ÚconfigÚespeak_voicer'   r"   )Údefault_model_idÚdefault_voiceÚlast_synthesisr"   r#   Úapp_infov   s   ýúzmain.<locals>.app_infoz/voicesc               	      s´   i } t ˆ› d�ƒg}ˆ jD ]}t |ƒ d¡D ]}t |› d�ƒ}| ¡ r(| |¡ qq|D ]+}|j d¡}|| v r9q,t|ddd��}t 	|¡| |< W d  ƒ n1 sRw   Y  q,| S )zÒList downloaded voices.

        Outputs a JSON object with the format:
        {
          "<voice name>": { <voice config> },
          ...
        }

        for each voice in your data directories.
        z.jsonz*.onnxz
.onnx.jsonÚrzutf-8)ÚencodingN)
r   Údata_dirÚglobÚexistsr   r%   ÚrstripÚopenÚjsonÚload)Úvoices_dictÚconfig_pathsr2   Ú	onnx_pathÚconfig_pathÚmodel_idÚconfig_file)ÚargsÚ
model_pathr"   r#   Ú
app_voices•   s$   

€ýÿ€zmain.<locals>.app_voicesz/all-voicesc                  S   s6   t tƒ�} t | ¡W  d  ƒ S 1 sw   Y  dS )z List all Piper voices.

        Outputs voices.json from the piper-voices repo on HuggingFace.
        See: https://huggingface.co/rhasspy/piper-voices
        N)r   r   r7   r8   )Úresponser"   r"   r#   Úapp_all_voices´   s   
$ÿzmain.<locals>.app_all_voicesz	/downloadÚPOSTc                     s@   t  tj¡} |  d¡}|stdƒ‚|  dd¡}t|ˆ |d� |S )aÌ  Download a voice.

        Downloads the .onnx and .onnx.json file from piper-voices repo on HuggingFace.
        See: https://huggingface.co/rhasspy/piper-voices

        Expects a JSON object with the format:
        {
          "voice": "<voice name>",   (required)
          "force_redownload": false  (optional)
        }

        Returns the name of the voice.
        Voice format must be <language>-<name>-<quality> like "en_US-lessac-medium".
        r(   zvoice is requiredÚforce_redownloadF)rE   )r7   Úloadsr
   ÚdataÚgetÚ
ValueErrorr   )rG   r=   rE   )Údownload_dirr"   r#   Úapp_download¾   s   
zmain.<locals>.app_downloadz/synthesizec               
      s  t  tj¡} |  dd¡ ¡ }|stdƒ‚t | ¡ |  dˆ¡}ˆ |¡}|du rOˆ j	D ]#}t
|ƒ|› d� }| ¡ rNt d|¡ tj|ˆ jd�}|ˆ|<  nq+|du r[t d	|¡ ˆ}|  d
¡}|jjdkrŽ|du rŽ|  d¡}|rx|jj |¡}|du rŽt d||jj ¡ ¡ ˆ jp�|jj}|durš||jjkršd}t|t|  dˆ jdur¨ˆ jn|jj¡ƒt|  dˆ jdur¹ˆ jn|jj¡ƒt|  dˆ jdurÊˆ jn|jj¡ƒd�}t d||¡ g }	g }
t ¡ }t ¡ �˜}t  |d¡}|�h d}t!|j"||dd�ƒD ]S\}}|�s| #|j$¡ | %|j&¡ | '|j(¡ d}|dk�r+| )t*t+|jj$ˆ j, d ƒƒ¡ | )|j-¡ |	 .|j/¡ |j0�p<g D ]}|
 1|j2|j3|j$ dœ¡ �q=qûW d  ƒ n	1 �sZw   Y  t ¡ | }ˆ 4¡  ˆj5|||	|
d� | 6¡ W  d  ƒ S 1 �s�w   Y  dS )aç  Synthesize audio from text.

        Expects a JSON object with the format:
        {
          "text": "Text to speak.",      (required)
          "voice": "<voice name>",       (optional)
          "speaker": "<speaker name>",   (optional)
          "speaker_id": "<speaker id>",  (optional, overrides speaker)
          "length_scale": 1.0,           (optional)
          "noise_scale": 0.667,          (optional)
          "length_w_scale": 0.8          (optional)
        }
        ÚtextÚ zNo text providedr(   Nr   zLoading voice %s)r   z)Voice not found: %s. Using default voice.Ú
speaker_idr   ÚspeakerzSpeaker not found: '%s' in %sr   Úlength_scaleÚnoise_scaleÚnoise_w_scale)rN   rP   rQ   rR   z&Synthesizing text: '%s' with config=%sÚwbFT)r   é   )ÚphonemeÚseconds)rL   Úsynthesize_secondsÚphonemesÚ
alignments)7r7   rF   r
   rG   rH   ÚstriprI   Ú_LOGGERÚdebugr2   r   r4   r   r8   ÚcudaÚwarningr*   r'   Úspeaker_id_mapÚkeysrO   Údefault_speaker_idr   ÚfloatrP   rQ   rR   ÚtimeÚ	monotonicÚioÚBytesIOÚwaver6   Ú	enumerateÚ
synthesizeÚsetframerateÚsample_rateÚsetsampwidthÚsample_widthÚsetnchannelsÚsample_channelsÚwriteframesÚbytesÚintÚsentence_silenceÚaudio_int16_bytesÚextendrX   Úphoneme_alignmentsr   rU   Únum_samplesÚclearÚupdateÚgetvalue)rG   rL   r=   r(   r2   Úmaybe_model_pathrN   rO   Ú
syn_configrX   rY   Ú
start_timeÚwav_ioÚwav_fileÚwav_params_setÚiÚaudio_chunkÚ	alignmentrW   )r?   r,   r-   r.   Úloaded_voicesr"   r#   Úapp_synthesizeØ   sÖ   


ü


ý
ÿûÿ

ÿûÿ

ÿûÿê"
ÿ
ÿÿÿÿþÿÿêþ!ü&Ôzmain.<locals>.app_synthesize)ÚhostÚportN)"ÚargparseÚArgumentParserÚadd_argumentrr   rb   Ústrr   ÚcwdÚ
parse_argsÚloggingÚbasicConfigr\   ÚDEBUGÚINFOr[   rJ   r2   Úmodelr4   rI   r%   r5   r   r8   r]   r   Ú__name__Úrouter   r   rq   Úrunr†   r‡   )ÚparserÚ
voice_namer2   r{   Úappr$   r/   rA   rC   rK   r…   r"   )r?   r,   r-   rJ   r.   r„   r@   r#   Úmain   s¦   ÿÿú	ûûýÿ



þ
ÿÿ 	 
r™   Ú__main__)r   N)Ú__doc__rˆ   re   r7   rŽ   rc   rg   Úpathlibr   Útypingr   r   r   r   Úurllib.requestr   Úflaskr   r	   r
   rM   r   r   Údownload_voicesr   r   Ú	getLoggerr[   r™   r“   r"   r"   r"   r#   Ú<module>   s(    
  R
ÿ