
     i)                        d dl mZ 	 d dlmZ d dlmZ dZd dl	Z	d dl
Z
d dlmZ d dlmZ d dlZ	 d dlmZmZ d d	lmZ dZd d
l mZmZ d dlZd dlmZmZmZmZm Z m!Z! d dl"mZm#Z# d dl$m%Z% d dl&m'Z' dde#dee   ddfdZ(	 	 	 	 	 dde#dee   de)de*de+de,fdZ-	 	 	 	 dde%de)de*de+de,deee+f   fdZ.y# e$ r dZY w xY w# e$ r dZY w xY w)    )Union)Audio)VideoTFN)Path)	AudioClip	VideoClip)mplfig_to_npimage)MappingOptional)
AnnotationSegmentSlidingWindowSlidingWindowFeatureTimelinenotebook)r   	AudioFile)Model)Binarize
audio_filesegmentreturnc                     t         st        j                  d       y| t        d      |       \  }}nt        d      j	                  | |      \  }}t        |j                         |      S )ad  listen to audio

    Allows playing of audio files. It will play the whole thing unless
    given a `Segment` to crop to.

    Parameters
    ----------
    audio_file : AudioFile
        A str, Path or ProtocolFile to be loaded.
    segment : Segment, optional
        The segment to crop the playback to.
        Defaults to playback the whole file.
    z-You need IPython installed to use this methodNdownmix)mono)rate)IPYTHON_INSTALLEDwarningswarnr   cropIPythonAudioflatten)r   r   waveformsrs       q/Volumes/fast/ai/experiments/voice-extract-mac/.venv/lib/python3.12/site-packages/pyannote/audio/utils/preview.pylistenr%   C   sb     EF,u),Z8"),11*gF"((*44    zoom	video_fps	video_extdisplayc           
         t         st        j                  d       y|rt        st        j                  d       t	        | t
              r
d| v r| d   }n7t	        | t        t        f      rt        |       j                  }nt        d      t        j                  d      }| d| d	| }	t        d
d      }
|
j                  |       }t        d|      |
j                  |       \  j!                         j"                  t%        j&                  dz  dz        }t)        |      t+        j,                        t+        j.                        fdt0        ffd}t3        |j4                        }t7        j8                          t;              dz   }t=        j>                  |ddd|z  fd      \  }|dddf   ^ ddt0        ff	d}tA        |j4                        }|jC                  |      }|jE                  |	|ddd       t=        jF                         |s|	S tI        |	d       S )!a  Preview

    Parameters
    ----------
    audio_file : AudioFile
        A str, Path or ProtocolFile to be previewed
    segment : Segment, optional
        The segment to crop the preview to.
        Defaults to preview the whole file.
    video_fps : int, optional
        Video frame rate. Defaults to 5. Higher frame rate leads
        to a smoother video but longer processing time.
    video_ext : str, optional
        One of {"webm", "mp4", "ogv"} according to what your
        browser supports. Defaults to "webm" as it seems to
        be supported by most browsers (see caniuse.com/webm)/
    display : bool, optional
        Wrap the video in a IPython.display.Video instance for
        visualization in notebooks (default). Set to False if
        you are only interested in saving the video preview to
        disk.
    **views : dict
        Additional views. See Usage section below.

    Returns
    -------
    * IPython.display.Video instance if `display` is True (default)
    * path to video preview file if `display` is False

    Usage
    -----
    >>> assert isinstance(annotation, pyannote.core.Annotation)
    >>> assert isinstance(scores, pyannote.core.SlidingWindowFeature)
    >>> assert isinstance(timeline, pyannote.core.Timeline)
    >>> preview("audio.wav", reference=annotation, speech_probability=scores, speech_regions=timeline)
    # will create a video with 4 views. from to bottom:
    # "reference", "speech probability", "speech regions", and "waveform")

    z-You need MoviePy installed to use this methodNzSince IPython is not installed, this method cannot be used with default display=True option. Either run this method in a notebook or use display=False to save video preview to disk.urizUnsupported 'audio_file' type.zpyannote-audio-preview)prefix/.i>  r   )sample_rater   g        )startend   )r1   durationstepTc                     t        | t        j                        r6t        j                  | z  j	                  t        j
                              S t        | z           S N)
isinstancenpndarraytakeastypeint64round)r6   datar0   s    r$   make_audio_framez!preview.<locals>.make_audio_frame   sI    a$774!k/!9!9"((!CDDE!k/*++r&   )r4   fps
      F)nrowsncolsfigsizesqueezer   )gg?c                 N  	 | j                   z   }t        |dz  z
  |dz  z         t        _        j	                          t        j
                  
d       j                  ||gd       j                  j                         j                  d       j                  j                         j                  g        j                  d       t        	j                               D ]+  \  \  }}}|j	                          t        |t              rt        j                   ||d       nSt        |t"              rt        j$                  ||dd       n)t        |t&              rt        j
                  ||d       |j                  ||gd       |j                  j                         j                  d       |j                  j                         j                  g        |j                  d	j)                  |j+                  d
                   . t-              S )Ng      ?T)axtimeylimzk--r"   F)rJ   rK   )rJ   rK   legend _)r1   r   r   r   clearplot_featureplotaxes	get_yaxisset_visible	set_ticks
set_ylabelzipitemsr9   r   plot_timeliner   plot_annotationr   joinsplitr	   )r6   tnameviewax_viewax_viewsax_wavfigr   viewsr"   rL   ylim_waveformr'   s        r$   
make_framezpreview.<locals>.make_frame   s    C$JC$J?h6=Q 	QFM51 	++D1))"-*%%(%A!LT4'MMO$)&&teDD*-(('dSD"67%%dwUN LL!Qu- LL""$006LL""$..r2sxx

389' &B* !%%r&   )r4   T	ultrafastbar)rB   audio	audio_fpspresetlogger)embed)%MOVIEPY_INSTALLEDr   r   r   r9   r
   strr   r_   
ValueErrortempfilemkdtempr   get_durationr   r   numpyr6   r   r1   r   r:   minmaxfloatr   r4   r   resetlenpltsubplotsr   	set_audiowrite_videofilecloseIPythonVideo)r   r   r'   r(   r)   r*   re   r,   temp_dir
video_pathrj   r4   samplesrA   
audio_cliprE   rS   rg   
video_cliprb   rc   r@   rd   r0   r"   rL   rf   s    ``   `            @@@@@@@@r$   previewr   \   s2   b EF(M	
 *g&5J+>	Jd	,:##9::'?@H:Qse1YK0Je)4E%%j12 

:w7D+::<>>Dmma+oAOG $D'2HFF4L"&&,.M,E ,
 +g6F6FKXJ NN JNE1r1u9ouIC QT
Xv D'&e '& '&R :0@0@AJ%%j1J   IIcN
$//r&   modelblankc                    t        t        | j                                     }|d   j                  \  }}}|d   j                  \  }}	}
| j                  j
                  }t        ||||z  z   z        }t        | j                  |      d         }t        j                  d|f      }t        j                  ||
f      }t        t        |d   |d               D ]L  \  }\  }}t        ||||z  z   z        }||dd|||z   f<   | j                  |      \  }}|||||	z   ddf<   N  t               t        || j                  j                              }||dd}t        |||||      S )	a  Preview training samples of a given model

    Parameters
    ----------
    Model : Model
        Model, already setup for training (i.e. call model.setup(stage="fit") first).
    blank : float, optional
        Add blank of that many seconds between each sample. Defaults to 1.0
    video_fps : int, optional
        Video frame rate. Defaults to 5. Higher frame rate leads
        to a smoother video but longer processing time.
    video_ext : str, optional
        One of {"webm", "mp4", "ogv"} according to what your
        browser supports. Defaults to "webm" as it seems to
        be supported by most browsers (see caniuse.com/webm)/
    display : bool, optional
        Wrap the video in a IPython.display.Video instance for
        visualization in notebooks (default). Set to False if
        you are only interested in saving the video preview to
        disk.

    Returns
    -------
    * IPython.display.Video instance if `display` is True (default)
    * path to video preview file if `display` is False
    Xyr   r3   NTrainingSamples)r"   r0   r,   )r(   r)   r*   	reference)nextitertrain_dataloadershaperj   r0   intintrospectiontorchzeros	enumeraterX   r   r   framesr   )r   r   r(   r)   r*   batch
batch_sizenum_channelsnum_samples
num_framesnum_speakersr0   batch_num_samplesbatch_num_framesr"   r   br   r   X_idxy_idxrO   r   s                          r$   BROKEN_preview_training_samplesr     s   D e,,./0E,1#J,<,<)Jk+0:+;+;(J
L++))KJ+8K*KLM5../@A!DE{{A012H-|<=Is5:uSz:;	6AqAu{'::;<34EEK///0&&u-q34	%%*,,a/0	 < 
/	5;N;N;U;UVWI " J  r&   r8   )Ng      $@   webmT)g      ?r   r   T)/typingr   IPython.displayr   r    r   r   r   ImportErrorrr   r   pathlibr   matplotlib.pyplotpyplotr{   ru   r:   moviepy.editorr   r   moviepy.video.io.bindingsr	   ro   r
   r   r   pyannote.corer   r   r   r   r   r   pyannote.audio.core.ior   pyannote.audio.core.modelr   pyannote.audio.utils.signalr   r%   rx   r   rp   boolr   r    r&   r$   <module>r      s^  0 55     3;
 %   4 + 05y 58G+< 5 56 "&d0d0gd0 d0 	d0
 d0 d0R @@@ @ 	@
 @ <@I    s"   B1 B> 1B;:B;>CC