o
    pil                     @   sx   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	Z
d dlmZmZ d dlmZ d dlmZmZ G dd deZdS )	    N)Path)Optional)AssetFileNamedownload_from_hf_hub)IsotonicRegression)NotFittedErrorcheck_is_fittedc                       s   e Zd ZdZ fddZ	ddejdedejfdd	Zd
e	fddZ
ededd fddZed
e	dd fddZe				ddee	B de	dB de	dB de	eB dB dee	B dB ded  fddZ  ZS )CalibrationzLogit/distance calibrationc                    s   t  jddddd d S )Ng              ?autoclip)y_miny_max
increasingout_of_bounds)super__init__)self	__class__ S/home/ubuntu/.local/lib/python3.10/site-packages/pyannote/audio/core/calibration.pyr   (   s   zCalibration.__init__       @values	nan_valuereturnc                 C   s*   t j|d|d}| |}||jS )a  Apply calibration handling NaN values and any shape gracefully
        
        Parameters
        ----------
        values : np.ndarray
            Values to calibrate
        nan_value : float, optional
            Value to use in place of NaN values during calibration. Default is 2.0.

        Returns
        -------
        calibrated_values : np.ndarray
            Calibrated values
        )nan)np
nan_to_numreshape	transformshape)r   r   r   transformedr   r   r   safe_transform+   s   
zCalibration.safe_transformpathc                 C   sP   zt |  W n ty   tdw | j| j| j| j| jd}tj	|| dS )a  Save fitted calibration to disk

        Parameters
        ----------
        path : str
            Path to the file where the calibration should be saved

        Raises
        ------
        NotFittedError
            If the calibration is not fitted yet

        zCannot save an unfitted model.)X_min_X_max_X_thresholds_y_thresholds_increasing_N)
r   r   r&   r'   r(   r)   r*   safetensorsnumpy	save_file)r   r%   tensor_dictr   r   r   saveG   s   zCalibration.saver.   c                 C   s   |  }|  D ]
\}}t||| qtjjtt|jd g|jt	|jd ggtd|j
 g|jd|j
 ggddd|_|S )a  Load calibration from a dictionary of tensors

        Parameters
        ----------
        tensor_dict : dict
            Dictionary containing the calibration tensors

        Returns
        -------
        calibration : Calibration
            Fitted calibration
        r
   linearF)kindbounds_error)itemssetattrscipyinterpolateinterp1dr   hstackminr(   maxr*   r)   f_)clsr.   calibrationkeyvaluer   r   r   from_tensor_dictd   s(   

zCalibration.from_tensor_dictc                 C   s   t j|}| |S )zLoad calibration from disk

        Parameters
        ----------
        path : str
            Path to the file where the calibration is saved

        Returns
        -------
        calibration : Calibration
            Fitted calibration
        )r+   r,   	load_filer@   )r<   r%   r.   r   r   r   	from_file   s   
zCalibration.from_fileN
checkpoint	subfolderrevisiontoken	cache_dirc                 K   s   t j|r$|durtd|rt|| tjj }n7t|tjj }n.t j|r5|dur2td|}nt	|}d|v rAtdt
|tj||||d}|du rRdS | |S )a  Load calibration from disk or Huggingface Hub

        Parameters
        ----------
        checkpoint : Path or str
            Path to checkpoint or a model identifier from the hf.co model hub.
        subfolder : str, optional
            Folder inside the hf.co model repo.
        revision : str, optional
            Revision when loading from the huggingface.co model hub.
        token : str, optional
            When loading a private hf.co model, set `token`
            to True or to a string containing your hugginface.co authentication
            token that can be obtained by running `huggingface-cli login`
        cache_dir: Path or str, optional
            Path to model cache directory.
        Nz0Revisions cannot be used with local checkpoints.@z:Revisions must be passed with `revision` keyword argument.)rD   rE   rG   rF   )osr%   isdir
ValueErrorr   r   r	   r?   isfilestrr   rB   )r<   rC   rD   rE   rF   rG   kwargspath_to_calibration_checkpointr   r   r   from_pretrained   s8   	
zCalibration.from_pretrained)r   )NNNN)__name__
__module____qualname____doc__r   r   ndarrayfloatr$   rM   r/   classmethoddictr@   rB   r   boolr   rP   __classcell__r   r   r   r   r	   %   sD    
'

r	   )rI   pathlibr   typingr   r,   r   safetensors.numpyr+   scipy.interpolater5   pyannote.audio.utils.hf_hubr   r   sklearn.isotonicr   sklearn.utils.validationr   r   r	   r   r   r   r   <module>   s   