o
    ±ƒðj   ã                   @   sz   d Z ddlZddlZddlmZmZ ddlZe e¡Z		ddej
dee defdd„Zdefd	d
„Zedkr;eƒ  dS dS )z~Patches a voice ONNX model with phoneme width alignment output.

Requires the onnx package to be installed (not onnxruntime).
é    N)ÚOptionalÚSetÚmodelÚtensor_nameÚreturnc                    s¾   |r|‰ n5t ƒ }| jjD ]}|jdkrq| |j¡ q|s!tdƒ‚t|ƒdkr.td|› �ƒ‚tt	|ƒƒ‰ t
 dˆ ¡ t‡ fdd„| jjD ƒƒrNtdˆ › �ƒ‚tj ¡ }ˆ |_| jj |¡ ˆ S )	aÈ  Mark the model's w_ceil (Ceil) tensor as a graph output.

    The model is modified in place. This exposes the per-phoneme-id audio
    sample counts needed for alignments.

    :param model: ONNX model to modify in place.
    :param tensor_name: Name of tensor to mark as output (autodetected if None).
    :return: Name of the tensor that was marked as an output.
    :raises ValueError: If the tensor cannot be autodetected or is already an output.
    ÚCeilz7No ceil tensors detected. Provide tensor_name manually.é   z>Multiple ceil tensors detected, provide tensor_name manually: zDetected tensor name: %sc                 3   s   � | ]}|j ˆ kV  qd S ©N)Úname)Ú.0Úoutput©Úceil_tensor_name© ú¢/tmp/claude-1000/-var-www-html-academy/3f42efd1-c2b7-4d08-9b05-30d86bb35479/scratchpad/piper/venv/lib/python3.10/site-packages/piper/patch_voice_with_alignment.pyÚ	<genexpr>2   s   € z'add_alignment_output.<locals>.<genexpr>z$Tensor is already marked as output: )ÚsetÚgraphÚnodeÚop_typeÚupdater   Ú
ValueErrorÚlenÚnextÚiterÚ_LOGGERÚdebugÚanyÚonnxÚhelperÚValueInfoProtor
   Úappend)r   r   Úceil_tensor_namesr   Úceil_value_infor   r   r   Úadd_alignment_output   s.   
ÿÿ
r$   c               
   C   sÒ   t  ¡ } | jddd� | jddd� | jddd� |  ¡ }tjtjd� |js+|j|_t	 
|j¡}zt||jƒ}W n tyR } zt d	|¡ W Y d
}~dS d
}~ww t d|¡ t	 ||j¡ t d|j¡ dS )zMain entry point.r   zPath to ONNX voice model)Úhelpz--outputz/Path to write output model (default: overwrite)z--tensor-namez6Name of tensor to mark as output (default: autodetect))Úlevelz%sNr   zMarked tensor as output: %szSuccessfully wrote %sr   )ÚargparseÚArgumentParserÚadd_argumentÚ
parse_argsÚloggingÚbasicConfigÚINFOr   r   r   Úloadr$   r   r   r   ÚfatalÚinfoÚsave)ÚparserÚargsr   r   Úerrorr   r   r   Úmain<   s0   ÿÿ€þr5   Ú__main__r	   )Ú__doc__r'   r+   Útypingr   r   r   Ú	getLoggerÚ__name__r   Ú
ModelProtoÚstrr$   Úintr5   r   r   r   r   Ú<module>   s$    
ÿÿÿ
þ-!
ÿ