o
    pi90                     @   s   d dl mZ d dlmZmZmZ d dlZ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	ejd
ejfddZG dd deZG dd deZG dd deZdS )    )singledispatchmethod)DictListOptionalN)
AnnotationSegmentSlidingWindowSlidingWindowFeatureTimeline)
BaseMetric DetectionPrecisionRecallFMeasure)DiarizationErrorRate)	permutate	reference
hypothesisc           	      C   s   |  tj} | tj}t| tj |\\}}dt|  }tj|ddtj| dd }td|}td| }tj|| k| dd| }t|}t|}t|}|| | | }|||||dfS )a  Discrete diarization error rate

    Parameters
    ----------
    reference : (num_frames, num_speakers) np.ndarray
        Discretized reference diarization.
        reference[f, s] = 1 if sth speaker is active at frame f, 0 otherwise
    hypothesis : (num_frames, num_speakers) np.ndarray
        Discretized hypothesized diarization.
       hypothesis[f, s] = 1 if sth speaker is active at frame f, 0 otherwise

    Returns
    -------
    der : float
        (false_alarm + missed_detection + confusion) / total
    components : dict
        Diarization error rate components, in number of frames.
        Keys are "false alarm", "missed detection", "confusion", and "total".
          ?   )axisr   )false alarmmissed detection	confusiontotal)astypenphalfr   newaxissummaximum)	r   r   _r   detection_errorfalse_alarmmissed_detectionr   der r$   O/home/ubuntu/.local/lib/python3.10/site-packages/pyannote/audio/utils/metric.pydiscrete_diarization_error_rate)   s&   


r&   c                	   @   s   e Zd ZdZedd Zedd Z	ddee fdd	Z	e
	ddee fd
dZej	ddejdejdee fddZej	ddededee fddZdd ZdS )DiscreteDiarizationErrorRatez9Compute diarization error rate on discretized annotationsc                 C      dS )Nzdiscrete diarization error rater$   clsr$   r$   r%   metric_namec      z(DiscreteDiarizationErrorRate.metric_namec                 C      g dS N)r   r   r   r   r$   r)   r$   r$   r%   metric_componentsg      z.DiscreteDiarizationErrorRate.metric_componentsNuemc                 C   s   | j |||dS )Nr1   )compute_components_helper)selfr   r   r1   r$   r$   r%   compute_componentsk   s   z/DiscreteDiarizationErrorRate.compute_componentsc                 C   s   |j j}td| d)NzProviding hypothesis as z instances is not supported.)	__class____name__NotImplementedError)r4   r   r   r1   klassr$   r$   r%   r3   s   s   
z6DiscreteDiarizationErrorRate.compute_components_helperr   r   c                 C   s   |j dkr	td|d urtd|j\}}|j dkrtd|j\}}||kr,td||kr=t|dd|| ff}n||krMt|dd|| ff}t||d S )	N   z>Only (num_frames, num_speakers)-shaped reference is supported.z)`uem` is not supported with numpy arrays.z?Only (num_frames, num_speakers)-shaped hypothesis is supported.z=reference and hypothesis must have the same number of frames.)r   r   r   r   )ndimr8   
ValueErrorshaper   padr&   )r4   r   r   r1   ref_num_framesref_num_speakershyp_num_frameshyp_num_speakersr$   r$   r%   der_from_ndarray|   s2   



z-DiscreteDiarizationErrorRate.der_from_ndarrayc                 C   s  |j j}|dk s|dkrtd|dkr|j}|j}n |dkr;|j}|j j\}}	}
t|d j||d  j}|j	|	 }|j
||d}|dkr|d u rR| |j |j S t|g|s^td|  }|D ]"}||}||}| ||}| jD ]}||  || 7  < qyqd|S |dkr|  }|D ]>\}}|d ur|t|gsq|j|dd	}t|	|jd }| |d | |d | }| jD ]}||  || 7  < qq|S d S )
Nr:      ziOnly (num_frames, num_speakers) or (num_chunks, num_frames, num_speakers)-shaped hypothesis is supported.r   r   )
resolutionz)`uem` must fully cover hypothesis extent.center)mode)datar;   r8   extentsliding_windowr=   r   startendduration
discretizer3   r
   coversr<   init_componentscropcomponents_min)r4   r   r   r1   r;   supportrE   chunks
num_chunks
num_framesr   
componentssegmenthrsegment_componentnamewindowhypothesis_windowreference_windowcommon_num_frameswindow_componentsr$   r$   r%   der_from_swf   sX   






z)DiscreteDiarizationErrorRate.der_from_swfc                 C       |d |d  |d  |d  S Nr   r   r   r   r$   r4   rX   r$   r$   r%   compute_metric      z+DiscreteDiarizationErrorRate.compute_metricN)r7   
__module____qualname____doc__classmethodr+   r/   r   r
   r5   r   r3   registerr   ndarrayrC   r	   r   rc   rg   r$   r$   r$   r%   r'   `   sD    


(Gr'   c                       sZ   e Zd Zddef fddZedd Zedd Z		dd
ee	 fddZ
dd Z  ZS )SlidingDiarizationErrorRate      $@r^   c                    s   t    || _d S ri   )super__init__r^   )r4   r^   r6   r$   r%   rs      s   

z$SlidingDiarizationErrorRate.__init__c                 C   r(   )Nzwindow diarization error rater$   r)   r$   r$   r%   r+      r,   z'SlidingDiarizationErrorRate.metric_namec                 C   r-   r.   r$   r)   r$   r$   r%   r/      r0   z-SlidingDiarizationErrorRate.metric_componentsNr1   c                 C   sd   |d u rt dt }t| jd| j d}||D ]}|||||t|gd}q|d d  S )Nz9SlidingDiarizationErrorRate expects `uem` to be provided.g      ?)rM   stepr2   )r<   r   r   r^   rQ   r
   )r4   r   r   r1   r#   r^   chunkr   r$   r$   r%   r5     s   z.SlidingDiarizationErrorRate.compute_componentsc                 C   rd   re   r$   rf   r$   r$   r%   rg     rh   z*SlidingDiarizationErrorRate.compute_metric)rq   ri   )r7   rj   rk   floatrs   rm   r+   r/   r   r
   r5   rg   __classcell__r$   r$   rt   r%   rp      s    


rp   c                       s   e Zd ZdZdd Zedd Z		ddee d	e	d
e	fddZ
 fddZ	ddedefddZdeee	f fddZd fdd	Zdd Z  ZS )MacroAverageFMeasurea   Compute macro-average F-measure

    Parameters
    ----------
    collar : float, optional
        Duration (in seconds) of collars removed from evaluation around
        boundaries of reference segments (one half before, one half after).
    beta : float, optional
        When beta > 1, greater importance is given to recall.
        When beta < 1, greater importance is given to precision.
        Defaults to 1.

    See also
    --------
    pyannote.metrics.detection.DetectionPrecisionRecallFMeasure
    c                 C   s   | j S ri   )classesr4   r$   r$   r%   r/   3  s   z&MacroAverageFMeasure.metric_componentsc                 C   r(   )NzMacro F-measurer$   r)   r$   r$   r%   r+   6  r,   z MacroAverageFMeasure.metric_name        r   rz   collarbetac                    sP   |   | _|| _t|  | _| _ | _ fdd| jD | _| 	  d S )Nc                    s"   i | ]}|t d d qS ))r}   r~   r$   r   ).0labelr~   r}   kwargsr$   r%   
<dictcomp>I  s    z1MacroAverageFMeasure.__init__.<locals>.<dictcomp>)
r+   metric_name_rz   setr/   rR   r}   r~   _sub_metricsreset)r4   rz   r}   r~   r   r$   r   r%   rs   :  s   
zMacroAverageFMeasure.__init__c                    s&   t    | j D ]}|  q
d S ri   )rr   r   r   values)r4   
sub_metricrt   r$   r%   r   P  s   

zMacroAverageFMeasure.resetNr   r   c                 K   sJ   |   }| j D ]\}}|d||g||g|d|||< q	|S )N)r   r   r1   r$   )rP   r   itemssubset)r4   r   r   r1   r   detailsr   r   r$   r$   r%   r5   U  s   

z'MacroAverageFMeasure.compute_componentsdetailc                 C   s   t t| S ri   )r   meanlistr   )r4   r   r$   r$   r%   rg   c  s   z#MacroAverageFMeasure.compute_metricFc                    sV   t  jdd}| j D ]\}}t||jd |< q|r)t|jddddd d |S )	NF)displayTOTALTrightc                 S   s
   d | S )Nz{0:.2f})format)fr$   r$   r%   <lambda>r  s   
 z-MacroAverageFMeasure.report.<locals>.<lambda>)indexsparsifyjustifyfloat_format)rr   reportr   r   abslocprint	to_string)r4   r   dfr   r   rt   r$   r%   r   f  s   	zMacroAverageFMeasure.reportc                 C   s   t dd | j D S )Nc                 S   s   g | ]}t |qS r$   )r   )r   r   r$   r$   r%   
<listcomp>y  s    z0MacroAverageFMeasure.__abs__.<locals>.<listcomp>)r   r   r   r   r{   r$   r$   r%   __abs__x  s   zMacroAverageFMeasure.__abs__)r|   r   ri   )F)r7   rj   rk   rl   r/   rm   r+   r   strrw   rs   r   r   r5   r   rg   r   r   rx   r$   r$   rt   r%   ry   !  s0    


ry   )	functoolsr   typingr   r   r   numpyr   pyannote.corer   r   r   r	   r
   pyannote.metrics.baser   pyannote.metrics.detectionr   pyannote.metrics.diarizationr    pyannote.audio.utils.permutationr   ro   r&   r'   rp   ry   r$   r$   r$   r%   <module>   s   7 ,