o
    ôôj÷  ã                   @   s  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mZm	Z	m
Z
mZ d dlZd dlm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 e e¡Zdeddfd	d
„Zde	de	fdd„Zde
eef dedefdd„Z dd„ Z!dd„ Z"dd„ Z#dd„ Z$dd„ Z%d"dd„Z&d#d d!„Z'dS )$é    N)Ú	find_spec)ÚPath)ÚAnyÚCallableÚDictÚTuple)Ú
DictConfig)ÚpyloggerÚ
rich_utilsÚcfgÚreturnc                 C   sŠ   |   d¡st d¡ dS | j  d¡rt d¡ t d¡ | j  d¡r.t d¡ tj| d	d
� | j  d¡rCt d¡ tj	| d	d	d� dS dS )z÷Applies optional utilities before the task is started.

    Utilities:
        - Ignoring python warnings
        - Setting tags from command line
        - Rich config printing

    :param cfg: A DictConfig object containing the config tree.
    Úextrasz*Extras config not found! <cfg.extras=null>NÚignore_warningsz<Disabling python warnings! <cfg.extras.ignore_warnings=True>ÚignoreÚenforce_tagsz.Enforcing tags! <cfg.extras.enforce_tags=True>T)Úsave_to_fileZprint_configz>Printing config tree with Rich! <cfg.extras.print_config=True>)Úresolver   )
ÚgetÚlogÚwarningr   ÚinfoÚwarningsÚfilterwarningsr
   r   Úprint_config_tree©r   © r   ú_/var/www/html/academy/tools/voices/clone/CosyVoice/third_party/Matcha-TTS/matcha/utils/utils.pyr      s   





þr   Ú	task_funcc                    s2   dt dttttf tttf f f‡ fdd„}|S )aÒ  Optional decorator that controls the failure behavior when executing the task function.

    This wrapper can be used to:
        - make sure loggers are closed even if the task function raises an exception (prevents multirun failure)
        - save the exception to a `.log` file
        - mark the run as failed with a dedicated file in the `logs/` folder (so we can find and rerun it later)
        - etc. (adjust depending on your needs)

    Example:
    ```
    @utils.task_wrapper
    def train(cfg: DictConfig) -> Tuple[Dict[str, Any], Dict[str, Any]]:
        ...
        return metric_dict, object_dict
    ```

    :param task_func: The task function to be wrapped.

    :return: The wrapped task function.
    r   r   c              
      sÄ   z@z	ˆ | d�\}}W n t y } zt d¡ |‚d }~ww W t d| jj› �¡ tdƒr=dd l}|jr=t d¡ | 	¡  ||fS t d| jj› �¡ tdƒr`dd l}|jrat d¡ | 	¡  w w w )Nr   Ú zOutput dir: Úwandbr   zClosing wandb!)
Ú	Exceptionr   Ú	exceptionr   ÚpathsÚ
output_dirr   r   ÚrunÚfinish)r   Úmetric_dictÚobject_dictÚexr   ©r   r   r   ÚwrapI   s.   
€ùý
ö

ûztask_wrapper.<locals>.wrap)r   r   r   Ústrr   )r   r*   r   r)   r   Útask_wrapper3   s   .r,   r&   Úmetric_namec                 C   sR   |s	t  d¡ dS || vrtd|› d�ƒ‚| |  ¡ }t  d|› d|› d�¡ |S )zàSafely retrieves value of the metric logged in LightningModule.

    :param metric_dict: A dict containing metric values.
    :param metric_name: The name of the metric to retrieve.
    :return: The value of the metric.
    z7Metric name is None! Skipping metric value retrieval...Nz%Metric value not found! <metric_name=z†>
Make sure metric name logged in LightningModule is correct!
Make sure `optimized_metric` name in `hparams_search` config is correct!zRetrieved metric value! <ú=ú>)r   r   Ú
ValueErrorÚitem)r&   r-   Úmetric_valuer   r   r   Úget_metric_valuej   s   

ÿr3   c                 C   s(   |gt | ƒd d  }| |dd d…< |S )Né   é   )Úlen)Úlstr1   Úresultr   r   r   Úintersperse‚   s   r9   c                 C   s:   t j| j ¡ t jdd�}| | j ¡ d d d… d ¡}|S )Nr   )ÚdtypeÚsepéÿÿÿÿ)é   )ÚnpÚ
fromstringÚcanvasZtostring_rgbÚuint8ÚreshapeZget_width_height)ÚfigÚdatar   r   r   Úsave_figure_to_numpy‰   s   rE   c                 C   sb   t j d¡ t jdd�\}}|j| dddd�}t j||d� t  ¡  |j ¡  t	|ƒ}t  
¡  |S ©	NÚdefault)é   r=   )ÚfigsizeÚautoÚlowerÚnone)ÚaspectÚoriginÚinterpolation)Úax)ÚpltÚstyleÚuseÚsubplotsÚimshowÚcolorbarÚtight_layoutr@   ÚdrawrE   Úclose)ÚtensorrC   rP   ÚimrD   r   r   r   Úplot_tensor�   s   
r\   c                 C   sd   t j d¡ t jdd�\}}|j| dddd�}t j||d� t  ¡  |j ¡  t  	|¡ t  
¡  d S rF   )rQ   rR   rS   rT   rU   rV   rW   r@   rX   ÚsavefigrY   )rZ   ZsavepathrC   rP   r[   r   r   r   Ú	save_plot›   s   

r^   c                 C   sH   t | tjƒr| S t | tjƒr|  ¡  ¡  ¡ S t | tƒr t 	| ¡S t
dƒ‚)Nz.Unsupported type for conversion to numpy array)Ú
isinstancer>   ÚndarrayÚtorchÚTensorÚdetachÚcpuÚnumpyÚlistÚarrayÚ	TypeError)rZ   r   r   r   Úto_numpy¦   s   

ri   Ú
matcha_ttsc                 C   s®   t j d¡}|durt|ƒ ¡ jdd�}n4tjdkr6ddl}| 	|j
d¡}| |d¡\}}t|ƒjdd�}ntjd	krBtd
ƒ ¡ }nt ¡  d¡}| | ¡}|jddd� |S )zr
    Args:
        appname (str): Name of application

    Returns:
        Path: path to user data directory
    ÚMATCHA_HOMENF)ÚstrictÚwin32r   z@Software\Microsoft\Windows\CurrentVersion\Explorer\Shell FolderszLocal AppDataÚdarwinz~/Library/Application Support/z.local/shareT)ÚparentsÚexist_ok)ÚosÚenvironr   r   Ú
expanduserr   ÚsysÚplatformÚwinregÚOpenKeyÚHKEY_CURRENT_USERÚQueryValueExÚhomeÚjoinpathÚmkdir)Úappnamerk   Úansrv   ÚkeyÚdir_Ú_Z
final_pathr   r   r   Úget_user_data_dir±   s"   	
þ

r‚   Tc                 C   sˆ   t | ƒ ¡ rt d| › d�¡ td| › d�ƒ d S t d| › d�¡ td| › d�ƒ t| ƒ} |s;tj|| ddd� d S t	j|| d� d S )	Nz[+] Model already present at ú!z[-] Model not found at z! Will download itFT)ÚurlÚoutputÚquietÚfuzzy)r„   Úout)
r   Úexistsr   ÚdebugÚprintr   r+   ÚgdownÚdownloadÚwget)Úcheckpoint_pathr„   Zuse_wgetr   r   r   Úassert_model_downloadedÐ   s   r�   )rj   )T)(rq   rt   r   Úimportlib.utilr   Úpathlibr   Útypingr   r   r   r   rŒ   Úmatplotlib.pyplotÚpyplotrQ   re   r>   ra   rŽ   Ú	omegaconfr   Zmatcha.utilsr	   r
   Úget_pyloggerÚ__name__r   r   r,   r+   Úfloatr3   r9   rE   r\   r^   ri   r‚   r�   r   r   r   r   Ú<module>   s0    
7
