o
    piM                     @   s   d dl mZmZmZmZmZ d dlmZ d dlm	Z	 ddl m
Z
 ddl mZ ddl mZ d dlmZ d d	lZd d	lZd d
lmZ d dlmZ d dlmZ G dd dZd	S )    )OptionalTextIOUnionDictAny)Path)OrderedDict   )PipelineInput)PipelineOutput)	Direction)FileLockN)Timeline)
Annotation)Trialc                	   @   s  e Zd ZdZdd Zedd Zejdd Zdd Zd	d
 Z	dd Z
dd Z	dBdee dee defddZdedefddZdedefddZ			dCdee dee dee defddZdd  Zd!edd fd"d#Zd!edd fd$d%Zed&d' Z		dDd(ed!ee d)ee defd*d+Zd(edd fd,d-Zd.edefd/d0ZdEd2d3Z de!fd4d5Z"d.ed6edefd7d8Z#ed9d: Z$d;e%d6efd<d=Z&d;e%d6e'e(e)f fd>d?Z*d;e%d6e'e(e)f fd@dAZ+dS )FPipelinezBase tunable pipelinec                 C   s"   t  | _t  | _t  | _d| _d S )NF)r   _parameters_instantiated
_pipelinestrainingself r   N/home/ubuntu/.local/lib/python3.10/site-packages/pyannote/pipeline/pipeline.py__init__0   s   
zPipeline.__init__c                 C   s   | j S N)	_trainingr   r   r   r   r   >   s   zPipeline.trainingc                 C   s$   || _ | j D ]\}}||_qd S r   )r   r   itemsr   )r   r   _pipeliner   r   r   r   B   s   c                 C   s&   | j dd}ttt| | S )NT)frozen)
parametershashtuplesorted_flattenr   )r   r    r   r   r   __hash__I   s   zPipeline.__hash__c                 C   s   d| j v r| j d }||v r|| S d| j v r$| j d }||v r$|| S d| j v r6| j d }||v r6|| S dt| j|}t|)z(Advanced) attribute getterr   r   r   z!'{}' object has no attribute '{}')__dict__formattype__name__AttributeError)r   namer   r   r   msgr   r   r   __getattr__N   s   





zPipeline.__getattr__c           	         s   ddl m}  fdd}| jd}| jd}| jd}t||r:|du r-d	}t||| j|| || < dS t|trV|du rId
}t||| j|| || < dS |durd |v rd|| < dS t|  | dS )a?  (Advanced) attribute setter

        If `value` is an instance of `Parameter`, store it in `_parameters`.
        elif `value` is an instance of `Pipeline`, store it in `_pipelines`.
        elif `value` isn't an instance of `Parameter` and `name` is in `_parameters`,
        store `value` in `_instantiated`.
        r	   )	Parameterc                     s   | D ]	} |v r| = qd S r   r   )dictsdr,   r   r   remove_fromr   s
   z)Pipeline.__setattr__.<locals>.remove_fromr   r   r   Nz>cannot assign hyper-parameters before Pipeline.__init__() callz;cannot assign sub-pipelines before Pipeline.__init__() call)		parameterr/   r'   get
isinstancer+   r   object__setattr__)	r   r,   valuer/   r3   r   r   r   r-   r   r2   r   r8   f   s0   


zPipeline.__setattr__c                 C   sR   || j v r| j |= d S || jv r| j|= d S || jv r!| j|= d S t| | d S r   )r   r   r   r7   __delattr__)r   r,   r   r   r   r:      s   


zPipeline.__delattr__Fr    instantiatedreturnc           
         s   ddl m  |r|rd}t||rt| j}n|r' fdd| j D }nt| j}| j D ]\}}|j||d}| D ]\}}	|	|| d| < q@q1|S )aw  Get flattened dictionary of parameters

        Parameters
        ----------
        frozen : `bool`, optional
            Only return value of frozen parameters.
        instantiated : `bool`, optional
            Only return value of instantiated parameters.

        Returns
        -------
        params : `dict`
            Flattened dictionary of parameters.
        r	   Frozenz4one must choose between `frozen` and `instantiated`.c                    s"   i | ]\}}t | r||jqS r   )r6   r9   ).0npr=   r   r   
<dictcomp>   s
    z2Pipeline._flattened_parameters.<locals>.<dictcomp>r    r;   >)	r4   r>   
ValueErrordictr   r   r   r   _flattened_parameters)
r   r    r;   r-   paramspipeline_namer   pipeline_paramsr,   r9   r   r=   r   rG      s&   

zPipeline._flattened_parametersnested_paramsc                 C   sZ   t  }| D ]#\}}t|t r&| | D ]\}}||| d| < qq|||< q|S )a  Convert nested dictionary to flattened dictionary

        For instance, a nested dictionary like this one:

            ~~~~~~~~~~~~~~~~~~~~~
            param: value1
            pipeline:
                param: value2
                subpipeline:
                    param: value3
            ~~~~~~~~~~~~~~~~~~~~~

        becomes the following flattened dictionary:

            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            param                       : value1
            pipeline>param              : value2
            pipeline>subpipeline>param  : value3
            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        Parameter
        ---------
        nested_params : `dict`

        Returns
        -------
        flattened_params : `dict`
        rD   )rF   r   r6   r%   )r   rK   flattened_paramsr,   r9   subnamesubvaluer   r   r   r%      s   

zPipeline._flattenrL   c           
      C   s   i }dd | j D }| D ]'\}}|d}t|dkr1|d }d|dd }||| |< q|||< q| j  D ]\}}	|	|| ||< q;|S )a  Convert flattened dictionary to nested dictionary

        For instance, a flattened dictionary like this one:

            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            param                       : value1
            pipeline>param              : value2
            pipeline>subpipeline>param  : value3
            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        becomes the following nested dictionary:

            ~~~~~~~~~~~~~~~~~~~~~
            param: value1
            pipeline:
                param: value2
                subpipeline:
                    param: value3
            ~~~~~~~~~~~~~~~~~~~~~

        Parameter
        ---------
        flattened_params : `dict`

        Returns
        -------
        nested_params : `dict`
        c                 S   s   i | ]}|i qS r   r   )r?   r,   r   r   r   rB     s    z'Pipeline._unflatten.<locals>.<dictcomp>rD   r	   r   N)r   r   splitlenjoin
_unflatten)
r   rL   rK   rJ   r,   r9   tokensrI   
param_namer   r   r   r   rR      s   

zPipeline._unflattenNtrialc                    sR   |s|r durd}t || j||d} dur$ fdd| D }| |S )ag  Returns nested dictionary of (optionnaly instantiated) parameters.

        For a pipeline with one `param`, one sub-pipeline with its own param
        and its own sub-pipeline, it will returns something like:

        ~~~~~~~~~~~~~~~~~~~~~
        param: value1
        pipeline:
            param: value2
            subpipeline:
                param: value3
        ~~~~~~~~~~~~~~~~~~~~~

        Parameter
        ---------
        trial : `Trial`, optional
            When provided, use trial to suggest new parameter values
            and return them.
        frozen : `bool`, optional
            Return frozen parameter value
        instantiated : `bool`, optional
            Return instantiated parameter values.

        Returns
        -------
        params : `dict`
            Nested dictionary of parameters. See above for the actual format.
        Nz<One must choose between `trial`, `instantiated`, or `frozen`rC   c                    s   i | ]
\}}||| qS r   r   )r?   r,   paramrU   r   r   rB   ^  s    z'Pipeline.parameters.<locals>.<dictcomp>)rE   rG   r   rR   )r   rU   r    r;   r-   rH   r   rW   r   r!   2  s   #
zPipeline.parametersc                 C      dS )z8Instantiate root pipeline with current set of parametersNr   r   r   r   r   
initializec     zPipeline.initializerH   c                 C   s   ddl m} | D ]8\}}|| jv r+t|ts"d| d}t|| j| | q
|| jv r9t	| ||| q
d| d}t|| S )zRecursively freeze pipeline parameters

        Parameters
        ----------
        params : `dict`
            Nested dictionary of parameters.

        Returns
        -------
        self : `Pipeline`
            Pipeline.
        r	   r=   only parameters of 'z1' pipeline can be frozen (not the whole pipeline)parameter '' does not exist)
r4   r>   r   r   r6   rF   rE   freezer   setattr)r   rH   r>   r,   r9   r-   r   r   r   r^   g  s   



zPipeline.freezec                 C   s   ddl m} | D ]Z\}}|| jv r+t|ts"d| d}t|| j| | q
|| jv r[t	| |}t||rT|j
|krTd| d|j
 d| d}t| |j
}t| || q
d	| d
}t||   | S )zRecursively instantiate all pipelines

        Parameters
        ----------
        params : `dict`
            Nested dictionary of parameters.

        Returns
        -------
        self : `Pipeline`
            Instantiated pipeline.
        r	   r=   r[   z7' pipeline can be instantiated (not the whole pipeline)zParameter 'z%' is frozen: using its frozen value (z) instead of the one provided (z).r\   r]   )r4   r>   r   r   r6   rF   rE   instantiater   getattrr9   warningswarnr_   rY   )r   rH   r>   r,   r9   r-   rV   r   r   r   r`     s4   





zPipeline.instantiatec                 C   s0   t | |  }t | | jdd}||kS )zEWhether pipeline has been instantiated (and therefore can be applied)Tr;   )setr%   r!   )r   r!   r;   r   r   r   r;     s   zPipeline.instantiated
params_ymllossc              	   C   s   |du r
| j dd}d|i}|dur||d< tj|dd}t|d, t|d	d
}|| W d   n1 s;w   Y  W d   |S W d   |S 1 sSw   Y  |S )a  Dump parameters to disk

        Parameters
        ----------
        params_yml : `Path`
            Path to YAML file.
        params : `dict`, optional
            Nested Parameters. Defaults to pipeline current parameters.
        loss : `float`, optional
            Loss value. Defaults to not write loss to file.

        Returns
        -------
        content : `str`
            Content written in `param_yml`.
        NTrd   rH   rg   F)default_flow_stylez.lockwmode)r!   yamldumpr   with_suffixopenwrite)r   rf   rH   rg   contentcontent_ymlfpr   r   r   dump_params  s"   

zPipeline.dump_paramsc                 C   sJ   t |dd}tj|tjd}W d   n1 sw   Y  | |d S )zInstantiate pipeline using parameters from disk

        Parameters
        ----------
        param_yml : `Path`
            Path to YAML file.

        Returns
        -------
        self : `Pipeline`
            Instantiated pipeline

        rrj   )LoaderNrH   )ro   rl   load
SafeLoaderr`   )r   rf   rs   rH   r   r   r   load_params  s   zPipeline.load_paramsinputc                 C   s   t )z-Apply pipeline on input and return its outputNotImplementedError)r   rz   r   r   r   __call__  rZ   zPipeline.__call__ pyannote.metrics.base.BaseMetricc                 C      t  )a  Return new metric (from pyannote.metrics)

        When this method is implemented, the returned metric is used as a
        replacement for the loss method below.

        Returns
        -------
        metric : `pyannote.metrics.base.BaseMetric`
        r{   r   r   r   r   
get_metric  s   
zPipeline.get_metricc                 C   rX   )Nminimizer   r   r   r   r   get_direction  s   zPipeline.get_directionoutputc                 C   r   )a  Compute loss for given input/output pair

        Parameters
        ----------
        input : object
            Pipeline input.
        output : object
            Pipeline output

        Returns
        -------
        loss : `float`
            Loss value
        r{   )r   rz   r   r   r   r   rg     s   zPipeline.lossc                 C   rX   )Nrttmr   r   r   r   r   write_format(  rZ   zPipeline.write_formatfilec                 C   s   t | d| j ||S )zWrite pipeline output to file

        Parameters
        ----------
        file : file object
        output : object
            Pipeline output
        write_)ra   r   )r   r   r   r   r   r   rp   ,  s   
zPipeline.writec              
   C   s   t |tr|jdd}t |tr7|jddD ]\}}}d|j d|jdd|jdd	| d
	}|| qdS d|j	j
 d}t|)zWrite pipeline output to "rttm" file

        Parameters
        ----------
        file : file object
        output : `pyannote.core.Timeline` or `pyannote.core.Annotation`
            Pipeline output
        string)	generatorTyield_labelzSPEAKER z 1 .3f z <NA> <NA> z <NA> <NA>
NDumping z, instances to "rttm" files is not supported.)r6   r   to_annotationr   
itertracksuristartdurationrp   	__class__r*   r|   )r   r   r   stlliner-   r   r   r   
write_rttm8  s   


zPipeline.write_rttmc                 C   s   t |tr!|D ]}|j d|jdd|jdd}|| qdS t |trO|jddD ] \}}}|j d|jdd|jdd| d| d
}|| q,dS d|jj	 d}t
|)	zWrite pipeline output to "txt" file

        Parameters
        ----------
        file : file object
        output : `pyannote.core.Timeline` or `pyannote.core.Annotation`
            Pipeline output
        r   r   
NTr   r   z+ instances to "txt" files is not supported.)r6   r   r   r   endrp   r   r   r   r*   r|   )r   r   r   r   r   r   r   r-   r   r   r   	write_txtT  s   

 
,zPipeline.write_txt)FF)NFF)NN)r<   r~   ),r*   
__module____qualname____doc__r   propertyr   setterr&   r.   r8   r:   r   boolrF   rG   r%   rR   r   r!   rY   r^   r`   r;   r   floatstrrt   ry   r
   r   r}   r   r   r   rg   r   r   rp   r   r   r   r   r   r   r   r   r   r   -   sv    

1
/&:
1(3
	
(

r   )typingr   r   r   r   r   pathlibr   collectionsr   r
   r   r   filelockr   rl   rb   pyannote.corer   r   optuna.trialr   r   r   r   r   r   <module>   s   