
     i=$                         d dl mZmZmZmZmZ d dlZd dl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ee   d	ee   d
ee   fdZ G d d      Zy)    )DictMappingOptionalTupleUnionN)
AnnotationSlidingWindowSlidingWindowFeature)Label)DiarizationErrorRate)	InferenceBinarizenum_speakersmin_speakersmax_speakersc                     | xs |xs d}| xs |xs t         j                  }||kD  rt        d|dd|dd      ||k(  r|} | ||fS )av  Validate number of speakers

    Parameters
    ----------
    num_speakers : int, optional
        Number of speakers.
    min_speakers : int, optional
        Minimum number of speakers.
    max_speakers : int, optional
        Maximum number of speakers.

    Returns
    -------
    num_speakers : int or None
    min_speakers : int
    max_speakers : int or np.inf
       zQmin_speakers must be smaller than (or equal to) max_speakers (here: min_speakers=gz and max_speakers=z).)npinf
ValueErrorr   r   r   s      /Volumes/fast/ai/experiments/voice-extract-mac/.venv/lib/python3.12/site-packages/pyannote/audio/pipelines/utils/diarization.pyset_num_speakersr   "   sx    0  4<41L9<9266Ll"##/"22D\RSDTTVX
 	
 |##|33    c                      e Zd ZdZe	 	 	 ddee   dee   dee   fd       Ze	 ddee	e
f   de
d	ed
ee
ee
eeef   f   f   fd       Ze	 ddededeeef   d
efd       Ze	 	 ddededed
e
fd       Zededed
efd       Zd Zy)SpeakerDiarizationMixinzBDefines a bunch of methods common to speaker diarization pipelinesNr   r   r   c                     t        | ||      S )a  Validate number of speakers

        Parameters
        ----------
        num_speakers : int, optional
            Number of speakers.
        min_speakers : int, optional
            Minimum number of speakers.
        max_speakers : int, optional
            Maximum number of speakers.

        Returns
        -------
        num_speakers : int or None
        min_speakers : int
        max_speakers : int or np.inf
        r   )r   r   s      r   r   z(SpeakerDiarizationMixin.set_num_speakersK   s    .  %%%
 	
r   	reference
hypothesisreturn_mappingreturnc                     t        | t              r| d   } d| v r| d   nd}nd}t               j                  | ||      }|j	                  |      }|r||fS |S )a  Find the optimal bijective mapping between reference and hypothesis labels

        Parameters
        ----------
        reference : Annotation or Mapping
            Reference annotation. Can be an Annotation instance or
            a mapping with an "annotation" key.
        hypothesis : Annotation
            Hypothesized annotation.
        return_mapping : bool, optional
            Return the label mapping itself along with the mapped annotation. Defaults to False.

        Returns
        -------
        mapped : Annotation
            Hypothesis mapped to reference speakers.
        mapping : dict, optional
            Mapping between hypothesis (key) and reference (value) labels
            Only returned if `return_mapping` is True.
        
annotation	annotatedN)uem)mapping)
isinstancer   r   optimal_mappingrename_labels)r    r!   r"   r&   r(   mapped_hypothesiss         r   r*   z'SpeakerDiarizationMixin.optimal_mappingh   s|    6 i)!,/I2=2J	+.PTII&(88zy 9 
 '44W4E$g-- %$r   binarized_segmentationsframeswarm_upc                    t        j                  | |      }t        j                  t        j                  |dd      |ddd      }t        j
                  |j                        j                  t        j                        |_        |S )a  Estimate frame-level number of instantaneous speakers

        Parameters
        ----------
        binarized_segmentations : SlidingWindowFeature
            (num_chunks, num_frames, num_classes)-shaped binarized scores.
        warm_up : (float, float) tuple, optional
            Left/right warm up ratio of chunk duration.
            Defaults to (0.1, 0.1), i.e. 10% on both sides.
        frames : SlidingWindow
            Frames resolution. Defaults to estimate it automatically based on
            `segmentations` shape and chunk size. Providing the exact frame
            resolution (when known) leads to better temporal precision.

        Returns
        -------
        count : SlidingWindowFeature
            (num_frames, 1)-shaped instantaneous speaker count
        )r/   T)axiskeepdimsF        hammingmissingskip_average)	r   trim	aggregater   sumrintdataastypeuint8)r-   r.   r/   trimmedcounts        r   speaker_countz%SpeakerDiarizationMixin.speaker_count   sk    4 ..!8'J##FF7d3
 WWUZZ(//9
r   discrete_diarizationmin_duration_onmin_duration_offc                 0    t        dd||      } ||       S )a  

        Parameters
        ----------
        discrete_diarization : SlidingWindowFeature
            (num_frames, num_speakers)-shaped discrete diarization
        min_duration_on : float, optional
            Defaults to 0.
        min_duration_off : float, optional
            Defaults to 0.

        Returns
        -------
        continuous_diarization : Annotation
            Continuous diarization, with speaker labels as integers,
            corresponding to the speaker indices in the discrete diarization.
        g      ?)onsetoffsetrD   rE   r   )rC   rD   rE   binarizes       r   to_annotationz%SpeakerDiarizationMixin.to_annotation   s(    0 +-	
 ,--r   segmentationsrA   c                    t        j                  | |j                  ddd      }|j                  j                  \  }}t        j                  |j                        }||k  r,t        j                  |j                  dd||z
  ff      |_        |j                  |j                  z  }|j                  |d      }|j                  |d      }t        j                  | d	      }t        j                  |j                        }t        t        ||            D ]3  \  }	\  \  }}
}t        |
j                               D ]  }d
||	||   f<    5 t!        ||j                        S )a  Build diarization out of preprocessed segmentation and precomputed speaker count

        Parameters
        ----------
        segmentations : SlidingWindowFeature
            (num_chunks, num_frames, num_speakers)-shaped segmentations
        count : SlidingWindow_feature
            (num_frames, 1)-shaped speaker count

        Returns
        -------
        discrete_diarization : SlidingWindowFeature
            Discrete (0s and 1s) diarization.
        Fr4   Tr5   )r   r   r   )return_datar1   )r2   g      ?)r   r:   sliding_windowr=   shaper   maxpadextentcropargsort
zeros_like	enumerateziprangeitemr
   )rK   rA   activations_r   max_speakers_per_framerR   sorted_speakersbinarytcspeakersis                r   to_diarizationz&SpeakerDiarizationMixin.to_diarization   sK   *  ))  
 &**00<!#

!300!vv  6A/E/T+U"V K ##ell2!&&v5&A

6u
5**k\;{//0%.s5//J%K!A!A1668_),q(1+~& % &L $FK,F,FGGr   c              #   ,   K   d}	 d|d |dz  }w)Nr   SPEAKER_02dr    )selfspeakers     r   classeszSpeakerDiarizationMixin.classes  s+     WSM**qLG s   NNN)F))皙?rl   )r4   r4   )__name__
__module____qualname____doc__staticmethodr   intr   r   r   r   boolr   r   r   r*   r
   r	   floatrB   rJ   rc   rj   rg   r   r   r   r   H   sl   L&*&*&*
sm
sm
 sm
 
8   %)%*,-)%)% )% 
z5T%,-?!?@@	A	)% )%X  (2#!5## ue|$# 
	# #J  "%"%.2..  . 
	. .@ /H+/H#/H 
/H /Hbr   r   rk   )typingr   r   r   r   r   numpyr   pyannote.corer   r	   r
   pyannote.core.utils.typesr   pyannote.metrics.diarizationr   pyannote.audio.core.inferencer   pyannote.audio.utils.signalr   rr   r   r   rg   r   r   <module>r|      se   . 9 8  I I + = 3 0 #'"&"&#43-#43-#4 3-#4LJ Jr   