o
    piV                     @   s:  d Z ddlmZmZmZ ddlZddlmZm	Z	 ddl
mZ ddlmZmZ ddlmZ dd	lmZ dd
lmZ ddlmZmZ ddlmZ erI	 dZG dd deZG dd deZdZdZdZG dd deZdZ dZ!dZ"G dd deeZ#dZ$G dd de#Z%dZ&d Z'd!Z(G d"d# d#eeZ)d$Z*G d%d& d&e)Z+dS )'zMetrics for diarization    )OptionalDictTYPE_CHECKINGN)
AnnotationTimeline)Label   )
BaseMetric	f_measure)IdentificationErrorRate)GreedyMapper)HungarianMapper)DetailsMetricComponents)UEMSupportMixinzdiarization error ratec                       s   e Zd ZdZedefddZddedef fd	d
Z		dde
de
dee deeef fddZ	dde
de
dee def fddZ  ZS )DiarizationErrorRateaL  Diarization error rate

    First, the optimal mapping between reference and hypothesis labels
    is obtained using the Hungarian algorithm. Then, the actual diarization
    error rate is computed as the identification error rate with each hypothesis
    label translated into the corresponding reference label.

    Parameters
    ----------
    collar : float, optional
        Duration (in seconds) of collars removed from evaluation around
        boundaries of reference segments.
    skip_overlap : bool, optional
        Set to True to not evaluate overlap regions.
        Defaults to False (i.e. keep overlap regions).

    Examples
    --------
    * Diarization error rate between `reference` and `hypothesis` annotations

        >>> metric = DiarizationErrorRate()
        >>> reference = Annotation(...)           # doctest: +SKIP
        >>> hypothesis = Annotation(...)          # doctest: +SKIP
        >>> value = metric(reference, hypothesis) # doctest: +SKIP

    * Compute global diarization error rate and confidence interval
      over multiple documents

        >>> for reference, hypothesis in ...      # doctest: +SKIP
        ...    metric(reference, hypothesis)      # doctest: +SKIP
        >>> global_value = abs(metric)            # doctest: +SKIP
        >>> mean, (lower, upper) = metric.confidence_interval() # doctest: +SKIP

    * Get diarization error rate detailed components

        >>> components = metric(reference, hypothesis, detailed=True) #doctest +SKIP

    * Get accumulated components

        >>> components = metric[:]                # doctest: +SKIP
        >>> metric['confusion']                   # doctest: +SKIP

    See Also
    --------
    :class:`pyannote.metric.base.BaseMetric`: details on accumulation
    :class:`pyannote.metric.identification.IdentificationErrorRate`: identification error rate

    returnc                 C      t S NDER_NAMEcls r   P/home/ubuntu/.local/lib/python3.10/site-packages/pyannote/metrics/diarization.pymetric_namee      z DiarizationErrorRate.metric_name        Fcollarskip_overlapc                    $   t  jd||d| t | _d S N)r   r   r   super__init__r   mapper_selfr   r   kwargs	__class__r   r   r$   i      zDiarizationErrorRate.__init__N	reference
hypothesisuemc                 C   $   |r| j |||d\}}| ||S )ai  Optimal label mapping

        Parameters
        ----------
        reference : Annotation
        hypothesis : Annotation
            Reference and hypothesis diarization
        uem : Timeline
            Evaluation map

        Returns
        -------
        mapping : dict
            Mapping between hypothesis (key) and reference (value) labels
        r.   uemifyr%   r'   r,   r-   r.   r   r   r   optimal_mappingm   s   z$DiarizationErrorRate.optimal_mappingc                    r   | j |||| j| jdd\}}}|jdd}|jdd}| ||}|j|d}tt| j||f|ddd	|S 
NTr.   r   r   returns_uemstring	generatorint)mappingr   Fr.   r   r   )r2   r   r   rename_labelsr4   r#   r   compute_componentsr'   r,   r-   r.   r(   r=   mappedr)   r   r   r@      &   

z'DiarizationErrorRate.compute_componentsr   Fr   )__name__
__module____qualname____doc__classmethodstrr   floatboolr$   r   r   r   r   r   r4   r   r@   __classcell__r   r   r)   r   r   3   s2    1

#r   c                       s   e Zd ZdZedd Zddedef fdd	Z	
dde	de	de
e deeef fddZ	
dde	de	de
e def fddZ  ZS )GreedyDiarizationErrorRatea  Greedy diarization error rate

    First, the greedy mapping between reference and hypothesis labels is
    obtained. Then, the actual diarization error rate is computed as the
    identification error rate with each hypothesis label translated into the
    corresponding reference label.

    Parameters
    ----------
    collar : float, optional
        Duration (in seconds) of collars removed from evaluation around
        boundaries of reference segments.
    skip_overlap : bool, optional
        Set to True to not evaluate overlap regions.
        Defaults to False (i.e. keep overlap regions).

    Examples
    --------
    * Greedy diarization error rate between `reference` and `hypothesis` annotations

        >>> metric = GreedyDiarizationErrorRate()
        >>> reference = Annotation(...)           # doctest: +SKIP
        >>> hypothesis = Annotation(...)          # doctest: +SKIP
        >>> value = metric(reference, hypothesis) # doctest: +SKIP

    * Compute global greedy diarization error rate and confidence interval
      over multiple documents

        >>> for reference, hypothesis in ...      # doctest: +SKIP
        ...    metric(reference, hypothesis)      # doctest: +SKIP
        >>> global_value = abs(metric)            # doctest: +SKIP
        >>> mean, (lower, upper) = metric.confidence_interval() # doctest: +SKIP

    * Get greedy diarization error rate detailed components

        >>> components = metric(reference, hypothesis, detailed=True) #doctest +SKIP

    * Get accumulated components

        >>> components = metric[:]                # doctest: +SKIP
        >>> metric['confusion']                   # doctest: +SKIP

    See Also
    --------
    :class:`pyannote.metric.base.BaseMetric`: details on accumulation

    c                 C   r   r   r   r   r   r   r   r      r   z&GreedyDiarizationErrorRate.metric_namer   Fr   r   c                    s(   t t| jd||d| t | _d S r!   )r#   rN   r$   r   r%   r&   r)   r   r   r$      s   z#GreedyDiarizationErrorRate.__init__Nr,   r-   r.   r   c                 C   r/   )ah  Greedy label mapping

        Parameters
        ----------
        reference : Annotation
        hypothesis : Annotation
            Reference and hypothesis diarization
        uem : Timeline
            Evaluation map

        Returns
        -------
        mapping : dict
            Mapping between hypothesis (key) and reference (value) labels
        r0   r1   r3   r   r   r   greedy_mapping   s   z)GreedyDiarizationErrorRate.greedy_mappingc                    r5   r6   )r2   r   r   r?   rO   r#   rN   r@   rA   r)   r   r   r@     rC   z-GreedyDiarizationErrorRate.compute_componentsrD   r   )rE   rF   rG   rH   rI   r   rK   rL   r$   r   r   r   r   r   rO   r   r@   rM   r   r   r)   r   rN      s2    0



rN   zjaccard error ratezspeaker errorzspeaker countc                	       st   e Zd ZdZedd ZedefddZd fd	d
	Z	dde	de	de
e defddZdedefddZ  ZS )JaccardErrorRateui  Jaccard error rate

    Parameters
    ----------
    collar : float, optional
        Duration (in seconds) of collars removed from evaluation around
        boundaries of reference segments.
    skip_overlap : bool, optional
        Set to True to not evaluate overlap regions.
        Defaults to False (i.e. keep overlap regions).

    Examples
    --------
    >>> metric = JaccardErrorRate()
    >>> reference = Annotation(...)           # doctest: +SKIP
    >>> hypothesis = Annotation(...)          # doctest: +SKIP
    >>> jer = metric(reference, hypothesis)   # doctest: +SKIP

    Reference
    ---------

    Second DIHARD Challenge Evaluation Plan. Version 1.1
    N. Ryant, K. Church, C. Cieri, A. Cristia, J. Du, S. Ganapathy, M. Liberman
    https://coml.lscp.ens.fr/dihard/2019/second_dihard_eval_plan_v1.1.pdf

    "The Jaccard error rate is based on the Jaccard index, a similarity measure
    used to evaluate the output of image segmentation systems. An optimal
    mapping between reference and system speakers is determined and for each
    pair the Jaccard index is computed. The Jaccard error rate is then defined
    as 1 minus the average of these scores. While similar to DER, it weights
    every speaker’s contribution equally, regardless of how much speech they
    actually produced.

    More concretely, assume we have N reference speakers and M system speakers.
    An optimal mapping between speakers is determined using the Hungarian
    algorithm so that each reference speaker is paired with at most one system
    speaker and each system speaker with at most one reference speaker. Then,
    for each reference speaker ref the speaker-specific Jaccard error rate
    JERref is computed as JERref = (FA + MISS) / TOTAL where

    - TOTAL is the duration of the union of reference and system speaker
      segments; if the reference speaker was not paired with a system
      speaker, it is the duration of all reference speaker segments
    - FA is the total system speaker time not attributed to the reference
      speaker; if the reference speaker was not paired with a system speaker,
      it is 0
    - MISS is the total reference speaker time not attributed to the system
      speaker; if the reference speaker was not paired with a system speaker,
      it is equal to TOTAL

    The Jaccard error rate then is the average of the speaker specific Jaccard
    error rates.

    JER and DER are highly correlated with JER typically being higher,
    especially in recordings where one or more speakers is particularly
    dominant. Where it tends to track DER is in outliers where the diarization
    is especially bad, resulting in one or more unmapped system speakers whose
    speech is not then penalized. In these cases, where DER can easily exceed
    500%, JER will never exceed 100% and may be far lower if the reference
    speakers are handled correctly."



    c                 C   r   r   )JER_NAMEr   r   r   r   r   u  r   zJaccardErrorRate.metric_namer   c                 C      t tgS r   )JER_SPEAKER_COUNTJER_SPEAKER_ERRORr   r   r   r   metric_componentsy  s   z"JaccardErrorRate.metric_componentsr   Fc                    r    r!   r"   r&   r)   r   r   r$     r+   zJaccardErrorRate.__init__Nr,   r-   r.   c                 K   s   | j |||| j| jdd\}}}|jdd}|jdd}| ||}|  }| D ]N}||d }|d u r9d}	n/||}
||}|
	|
  }| ||
  }|
 |
|  }|| | }	|t  d7  < |t  |	7  < q*|S )NTr7   r9   r:   r<         ?r   )r2   r   r   r?   r4   init_componentslabelsgetlabel_timelineunionsupportdurationcroprS   rT   )r'   r,   r-   r.   r(   r=   detailref_speakerhyp_speakerjerrhtotalfamissr   r   r   r@     s2   


z#JaccardErrorRate.compute_componentsr_   c                 C   s   |t  |t  S r   )rT   rS   r'   r_   r   r   r   compute_metric  s   zJaccardErrorRate.compute_metricrD   r   )rE   rF   rG   rH   rI   r   r   rU   r$   r   r   r   r   r@   rK   ri   rM   r   r   r)   r   rP   3  s$    A

FrP   purityre   correctc                	   @   s\   e Zd ZdZedd Zedd Z	ddeded	ee	 d
e
fddZde
d
efddZdS )DiarizationPurityzCluster purity

    A hypothesized annotation has perfect purity if all of its labels overlap
    only segments which are members of a single reference label.
    c                 C   r   r   )PURITY_NAMEr   r   r   r   r     r   zDiarizationPurity.metric_namec                 C   rR   r   PURITY_TOTALPURITY_CORRECTr   r   r   r   rU        z#DiarizationPurity.metric_componentsNr,   r-   r.   r   c                 K   sn   |   }d}d}| D ] }||}	||	 7 }||	 }
||
s%dn|
d d 7 }q||t< ||t< |S )Nr   r   )rW   rX   rZ   r]   r^   chartro   rp   )r'   r,   r-   r.   r(   r_   r]   largestlabelr\   rr   r   r   r   r@     s   
z$DiarizationPurity.compute_componentsr_   c                 C   s    |t  dkr|t |t   S dS )Nr   rV   rn   rh   r   r   r   ri     s   z DiarizationPurity.compute_metricr   )rE   rF   rG   rH   rI   r   rU   r   r   r   r   r@   rK   ri   r   r   r   r   rl     s"    


rl   coveragec                	       F   e Zd ZdZedd Z	ddededee de	f fd	d
Z
  ZS )DiarizationCoveragezCluster coverage

    A hypothesized annotation has perfect coverage if all segments from a
    given reference label are assigned to the same cluster.
    c                 C   r   r   )COVERAGE_NAMEr   r   r   r   r   	  r   zDiarizationCoverage.metric_nameNr,   r-   r.   r   c                       t t| j||fd|i|S Nr.   )r#   rw   r@   r'   r,   r-   r.   r(   r)   r   r   r@        
z&DiarizationCoverage.compute_componentsr   rE   rF   rG   rH   rI   r   r   r   r   r   r@   rM   r   r   r)   r   rw     s    
rw   homogeneityentropyzcross-entropyc                	       sn   e Zd ZdZedd Zedd Zdded	ef fd
dZ		dde
de
dee defddZdd Z  ZS )DiarizationHomogeneityaU  Cluster homogeneity

    Parameters
    ----------
    collar : float, optional
        Duration (in seconds) of collars removed from evaluation around
        boundaries of reference segments.
    skip_overlap : bool, optional
        Set to True to not evaluate overlap regions.
        Defaults to False (i.e. keep overlap regions).

    c                 C   r   r   )HOMOGENEITY_NAMEr   r   r   r   r   ,  r   z"DiarizationHomogeneity.metric_namec                 C   rR   r   )HOMOGENEITY_ENTROPYHOMOGENEITY_CROSS_ENTROPYr   r   r   r   rU   0  rq   z(DiarizationHomogeneity.metric_componentsr   Fr   r   c                    s&   t t| jdi | || _|| _d S )Nr   )r#   r   r$   r   r   r&   r)   r   r   r$   4  s   
zDiarizationHomogeneity.__init__Nr,   r-   r.   r   c                 K   s   |   }| j|||| j| jd\}}|| }t|}tj|dd}tj|dd}	tj||d}
t|
tj	|
d  |t
< tj||d}
tj||	d}t|
tj	|d  |t< |S )Nr>   r   )axisr   r   )rW   r2   r   r   npsummadividefilledlogr   r   )r'   r,   r-   r.   r(   r_   matrixr]   	rduration	hdurationratiohratior   r   r   r@   9  s(   
	
"
z)DiarizationHomogeneity.compute_componentsc                 C   s<   d|t   }d|t  }|dkr|dkrdS dS d||  S )NrV   r   r   )r   r   )r'   r_   	numeratordenominatorr   r   r   ri   ^  s   z%DiarizationHomogeneity.compute_metricrD   r   )rE   rF   rG   rH   rI   r   rU   rK   rL   r$   r   r   r   r   r@   ri   rM   r   r   r)   r   r     s$    

	
%r   completenessc                	       rv   )DiarizationCompletenessaV  Cluster completeness

    Parameters
    ----------
    collar : float, optional
        Duration (in seconds) of collars removed from evaluation around
        boundaries of reference segments.
    skip_overlap : bool, optional
        Set to True to not evaluate overlap regions.
        Defaults to False (i.e. keep overlap regions).

    c                 C   r   r   )COMPLETENESS_NAMEr   r   r   r   r   {  r   z#DiarizationCompleteness.metric_nameNr,   r-   r.   r   c                    ry   rz   )r#   r   r@   r{   r)   r   r   r@     r|   z*DiarizationCompleteness.compute_componentsr   r}   r   r   r)   r   r   m  s    
r   ),rH   typingr   r   r   numpyr   pyannote.corer   r   pyannote.core.utils.typesr   baser	   r
   identificationr   matcherr   r   typesr   r   utilsr   r   r   rN   rQ   rT   rS   rP   rm   ro   rp   rl   rx   rw   r   r   r   r   r   r   r   r   r   r   <module>   sD    { ,L