o
    Sir                     @   s   d dl Z d dlZd dlZd dl mZ d dlmZ e d dej	dej
fddZd	ej
dej
fd
dZG dd deZddejjdedejfddZdS )    N)pyplot)CallbackAggfigreturnc                 C   s:   t j| j t jdd}|| j ddd d }|S )z
    Save a matplotlib figure to a numpy array.

    Args:
        fig (Figure): Matplotlib figure object.

    Returns:
        ndarray: Numpy array representing the figure.
     )dtypesepN)   )np
fromstringcanvastostring_rgbuint8reshapeget_width_height)r   data r   A/home/ubuntu/.local/lib/python3.10/site-packages/vocos/helpers.pysave_figure_to_numpy
   s   
r   spectrogramc                 C   sv   |  tj} tjdd\}}|j| dddd}tj||d td td	 t	  |j
  t|}t  |S )
z
    Plot a spectrogram and convert it to a numpy array.

    Args:
        spectrogram (ndarray): Spectrogram data.

    Returns:
        ndarray: Numpy array representing the plotted spectrogram.
    )   r   )figsizeautolowernone)aspectorigininterpolation)axFramesChannels)astyper   float32pltsubplotsimshowcolorbarxlabelylabeltight_layoutr   drawr   close)r   r   r    imr   r   r   r   plot_spectrogram_to_numpy   s   



r/   c                   @   s   e Zd ZdZdd ZdS )GradNormCallbackz,
    Callback to log the gradient norm.
    c                 C   s   | dt| d S )N	grad_norm)loggradient_norm)selftrainermodelr   r   r   on_after_backward6   s   z"GradNormCallback.on_after_backwardN)__name__
__module____qualname____doc__r7   r   r   r   r   r0   1   s    r0          @r6   	norm_typec                    s6   dd |   D }tt fdd|D  }|S )z
    Compute the gradient norm.

    Args:
        model (Module): PyTorch model.
        norm_type (float, optional): Type of the norm. Defaults to 2.0.

    Returns:
        Tensor: Gradient norm.
    c                 S   s   g | ]
}|j d ur|j qS )N)grad).0pr   r   r   
<listcomp>E       z!gradient_norm.<locals>.<listcomp>c                    s   g | ]
}t |  qS r   )torchnormdetach)r?   gr=   r   r   rA   F   rB   )
parametersrC   rD   stack)r6   r=   grads
total_normr   rG   r   r3   :   s    r3   )r<   )
matplotlibnumpyr   rC   r   r%   pytorch_lightningr   useFigurendarrayr   r/   r0   nnModulefloatTensorr3   r   r   r   r   <module>   s    
"	