o
    pi)                     @   s  d dl mZ zd dlmZ d dlmZ dZW n ey!   dZY nw d dl	Z	d dl
Z
d dlmZ d dlmZ d dlZzd dlmZmZ d d	lmZ dZW n eyW   dZY nw 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dZ(					d#de#dee de)de*de+de,fddZ-				d$de%de)de*de+de,deee+f fd d!Z.dS )%    )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                 C   sT   t s	td dS |du rtdd| \}}ntdd| |\}}t| |d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sr r"   P/home/ubuntu/.local/lib/python3.10/site-packages/pyannote/audio/utils/preview.pylistenC   s   
r$         $@   webmzoom	video_fps	video_extdisplayc              
      s  t s	td dS |rtstd t| tr d| v r | d }nt| ttfr-t| j}nt	dt
jdd}| d| d	| }	td
dd}
du rV|
| }td|d|
| \ jtjd d d}t|ttf	dtffdd}t|jd}t  td }tj|ddd| fdd\}|dddf ^  ddtf 	
f	dd}t |jd}|!|}|j"|	|ddd d! t# |s|	S t$|	d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                    s4   t | tjrt |  tjS  t|   S N)
isinstancenpndarraytakeastypeint64round)r6   )datar0   r"   r#   make_audio_frame   s   z!preview.<locals>.make_audio_frame)r4   fps
      F)nrowsncolsfigsizesqueezer   )gg?c                    sF  | j  }t|d  |d  t_  tjdd ||gd j 	d j 
g  d t  D ]Y\\}}}|  t|tr]tj||dd nt|trltj||ddd nt|trztj||dd |||gd |j 	d |j 
g  |d	|d
 qEtS )Ng      ?T)axtimeylimzk--r    F)rH   rI   )rH   rI   legend _)r1   r   r   r   clearplot_featureplotaxes	get_yaxisset_visible	set_ticks
set_ylabelzipitemsr8   r   plot_timeliner   plot_annotationr   joinsplitr   )r6   tnameviewax_view)	ax_viewsax_wavfigr   viewsr    rJ   ylim_waveformr(   r"   r#   
make_frame   s*   




zpreview.<locals>.make_frame)r4   T	ultrafastbar)rA   audio	audio_fpspresetlogger)embed)%MOVIEPY_INSTALLEDr   r   r   r8   r	   strr   r]   
ValueErrortempfilemkdtempr   get_durationr   r   numpyr6   r   r1   r   r9   minmaxfloatr   r4   r   resetlenpltsubplotsr   	set_audiowrite_videofilecloseIPythonVideo)r   r   r(   r)   r*   r+   rc   r,   temp_dir
video_pathrh   r4   samplesr@   
audio_cliprD   rQ   re   
video_clipr"   )r`   ra   r?   rb   r0   r   rc   r    rJ   rd   r(   r#   preview\   sb   1





")

	r         ?modelblankc                 C   s"  t t|  }|d j\}}}|d j\}}	}
| jj}t||||   }t| |d }t	d|f}t	||
f}t
t|d |d D ]/\}\}}t||||   }||dd||| f< | |\}}|||||	 ddf< qHt t|| jj}||dd}t|||||d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shaperh   r0   intintrospectiontorchzeros	enumeraterV   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_idxrM   r   r"   r"   r#   BROKEN_preview_training_samples  s2   ""r   r7   )Nr%   r&   r'   T)r   r&   r'   T)/typingr   IPython.displayr   r   r   r~   r   ImportErrorrp   r   pathlibr   matplotlib.pyplotpyplotry   rs   r9   moviepy.editorr   r   moviepy.video.io.bindingsr   rm   r	   r
   r   pyannote.corer   r   r   r   r   r   pyannote.audio.core.ior   pyannote.audio.core.modelr   pyannote.audio.utils.signalr   r$   rv   r   rn   boolr   r   r"   r"   r"   r#   <module>   s~    	
 *
