Ë
    T^(h¨M  ã                   ó  — d Z ddlZddlmZmZmZ ddlZddlZddlm	Z	m
Z
 ddlmZ ddlmZ ddlmZmZmZmZmZmZ  e«       rddlZddlZ e«       rddlZ e«       rddlZ ej4                  e«      Z G d	„ d
e«      Zd
gZy)z%Feature extractor class for Pop2Pianoé    N)ÚListÚOptionalÚUnioné   )Úmel_filter_bankÚspectrogram)ÚSequenceFeatureExtractor)ÚBatchFeature)Ú
TensorTypeÚis_essentia_availableÚis_librosa_availableÚis_scipy_availableÚloggingÚrequires_backendsc                   ó  ‡ — e Zd ZdZg d¢Z	 	 	 	 	 	 	 ddedededededed	efˆ fd
„Zdej                  fd„Z
dej                  fd„Zdej                  dej                  dej                  fd„Zdej                  dej                  fd„Zd dej                  fd„Z	 d!dedededeeeef      fd„Z	 	 	 	 d"deej                  ee   eej                     eee      f   deeee   f   dedee   dee   deeeef      defd„Zˆ xZS )#ÚPop2PianoFeatureExtractora  
    Constructs a Pop2Piano feature extractor.

    This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExtractor`] which contains
    most of the main methods. Users should refer to this superclass for more information regarding those methods.

    This class extracts rhythm and preprocesses the audio before it is passed to the model. First the audio is passed
    to `RhythmExtractor2013` algorithm which extracts the beat_times, beat positions and estimates their confidence as
    well as tempo in bpm, then beat_times is interpolated and to get beatsteps. Later we calculate
    extrapolated_beatsteps from it to be used in tokenizer. On the other hand audio is resampled to self.sampling_rate
    and preprocessed and then log mel spectogram is computed from that to be used in our transformer model.

    Args:
        sampling_rate (`int`, *optional*, defaults to 22050):
            Target Sampling rate of audio signal. It's the sampling rate that we forward to the model.
        padding_value (`int`, *optional*, defaults to 0):
            Padding value used to pad the audio. Should correspond to silences.
        window_size (`int`, *optional*, defaults to 4096):
            Length of the window in samples to which the Fourier transform is applied.
        hop_length (`int`, *optional*, defaults to 1024):
            Step size between each window of the waveform, in samples.
        min_frequency (`float`, *optional*, defaults to 10.0):
            Lowest frequency that will be used in the log-mel spectrogram.
        feature_size (`int`, *optional*, defaults to 512):
            The feature dimension of the extracted features.
        num_bars (`int`, *optional*, defaults to 2):
            Determines interval between each sequence.
    ©Úinput_featuresÚ	beatstepsÚextrapolated_beatstepÚsampling_rateÚpadding_valueÚwindow_sizeÚ
hop_lengthÚmin_frequencyÚfeature_sizeÚnum_barsc           	      óD  •— t        ‰	| �  d|||dœ|¤Ž || _        || _        || _        || _        || _        || _        || _        t        | j                  dz  dz   | j                  | j                  t        | j                  dz  «      | j                  d d¬«      | _        y )N)r   r   r   é   é   Úhtk)Únum_frequency_binsÚnum_mel_filtersr   Úmax_frequencyr   ÚnormÚ	mel_scale© )ÚsuperÚ__init__r   r   r   r   r   r   r   r   ÚfloatÚmel_filters)
Úselfr   r   r   r   r   r   r   ÚkwargsÚ	__class__s
            €úx/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/models/pop2piano/feature_extraction_pop2piano.pyr)   z"Pop2PianoFeatureExtractor.__init__R   s¶   ø€ ô 	‰Ñð 	
Ø%Ø'Ø'ñ	
ð ò		
ð +ˆÔØ*ˆÔØ&ˆÔØ$ˆŒØ*ˆÔØ(ˆÔØ ˆŒÜ*Ø $× 0Ñ 0°AÑ 5¸Ñ:Ø ×-Ñ-Ø×,Ñ,Ü × 2Ñ 2°aÑ 7Ó8Ø×,Ñ,ØØô
ˆÕó    Úsequencec                 ó  — g }|D ]e  }t        j                  | j                  dz   «      dd }|j                  t	        ||| j                  | j
                  d| j                  ¬«      «       Œg t        j                  |«      }|S )z®
        Generates MelSpectrogram.

        Args:
            sequence (`numpy.ndarray`):
                The sequence of which the mel-spectrogram will be computed.
        r    Néÿÿÿÿg       @)ÚwaveformÚwindowÚframe_lengthr   Úpowerr+   )ÚnpÚhanningr   Úappendr   r   r+   Úarray)r,   r1   Ú	mel_specsÚseqr5   s        r/   Úmel_spectrogramz)Pop2PianoFeatureExtractor.mel_spectrogramt   s†   € ð ˆ	Øò 	ˆCÜ—Z‘Z × 0Ñ 0°1Ñ 4Ó5°c°rÐ:ˆFØ×ÑÜØ Ø!Ø!%×!1Ñ!1Ø#Ÿ™ØØ $× 0Ñ 0ôõ	ð	ô —H‘H˜YÓ'ˆ	àÐr0   Úaudioc                 ó†   — t        | dg«       t        j                  j                  d¬«      } ||«      \  }}}}}|||||fS )a’  
        This algorithm(`RhythmExtractor2013`) extracts the beat positions and estimates their confidence as well as
        tempo in bpm for an audio signal. For more information please visit
        https://essentia.upf.edu/reference/std_RhythmExtractor2013.html .

        Args:
            audio(`numpy.ndarray`):
                raw audio waveform which is passed to the Rhythm Extractor.
        ÚessentiaÚmultifeature)Úmethod)r   rA   ÚstandardÚRhythmExtractor2013)r,   r?   Úessentia_trackerÚbpmÚ
beat_timesÚ
confidenceÚ	estimatesÚessentia_beat_intervalss           r/   Úextract_rhythmz(Pop2PianoFeatureExtractor.extract_rhythm�   sS   € ô 	˜$  Ô-Ü#×,Ñ,×@Ñ@ÈÐ@ÓWÐÙJZÐ[`ÓJaÑGˆˆZ˜ YÐ0Gà�J 
¨IÐ7NÐNÐNr0   rH   Ústeps_per_beatÚn_extendc                 ó  — t        | dg«       t        j                  j                  t	        j
                  |j                  «      |dd¬«      } |t	        j                  d|j                  |z   dz
  |j                  |z  |z   «      «      }|S )a  
        This method takes beat_times and then interpolates that using `scipy.interpolate.interp1d` and the output is
        then used to convert raw audio to log-mel-spectrogram.

        Args:
            beat_times (`numpy.ndarray`):
                beat_times is passed into `scipy.interpolate.interp1d` for processing.
            steps_per_beat (`int`):
                used as an parameter to control the interpolation.
            n_extend (`int`):
                used as an parameter to control the interpolation.
        ÚscipyFÚextrapolate)Úbounds_errorÚ
fill_valuer   r    )r   rP   ÚinterpolateÚinterp1dr8   ÚarangeÚsizeÚlinspace)r,   rH   rM   rN   Úbeat_times_functionÚ	ext_beatss         r/   Úinterpolate_beat_timesz0Pop2PianoFeatureExtractor.interpolate_beat_times�   s†   € ô  	˜$  	Ô*Ü#×/Ñ/×8Ñ8Ü�I‰I�j—o‘oÓ&ØØØ$ð	 9ó 
Ðñ (Ü�K‰K˜˜:Ÿ?™?¨XÑ5¸Ñ9¸:¿?¹?È^Ñ;[Ð^fÑ;fÓgó
ˆ	ð Ðr0   Úbeatstepc                 óÖ  — |�1t        |j                  «      dk7  rt        d|j                  › d�«      ‚|d   dkD  r||d   z
  }| j                  dz  }t        |«      }| j	                  |d| j                  dz   dz  dz   ¬«      }g }d}t        d||«      D ]k  }|}	t        ||z   |«      }
t        ||	   | j                  z  «      }t        ||
   | j                  z  «      }|j                  ||f«       t        |||z
  «      }Œm g }|D ]G  \  }}||| }t        j                  |d||j                  d   z
  ffdd¬	«      }|j                  |«       ŒI t        j                  |«      }||fS )
aƒ  
        Preprocessing for log-mel-spectrogram

        Args:
            audio (`numpy.ndarray` of shape `(audio_length, )` ):
                Raw audio waveform to be processed.
            beatstep (`numpy.ndarray`):
                Interpolated values of the raw audio. If beatstep[0] is greater than 0.0, then it will be shifted by
                the value at beatstep[0].
        r    zUExpected `audio` to be a single channel audio input of shape `(n, )` but found shape ú.r   g        é   ©rH   rM   rN   Úconstant©Úconstant_values)ÚlenÚshapeÚ
ValueErrorr   r[   ÚrangeÚminÚintr   r:   Úmaxr8   ÚpadÚasarray)r,   r?   r\   Ú	num_stepsÚnum_target_stepsr   Úsample_indicesÚmax_feature_lengthÚiÚ	start_idxÚend_idxÚstart_sampleÚ
end_sampleÚpadded_batchÚfeatureÚpadded_features                   r/   Úpreprocess_melz(Pop2PianoFeatureExtractor.preprocess_mel»   sÀ  € ð Ð¤ U§[¡[Ó!1°QÒ!6ÜØgÐhm×hsÑhsÐgtÐtuÐvóð ð �A‰;˜ÒØ (¨1¡+Ñ-ˆHà—M‘M AÑ%ˆ	Ü˜x›=ÐØ $× ;Ñ ;Ø°¸T¿]¹]ÈQÑ=NÐRSÑ<SÐVWÑ<Wð !<ó !
Ðð ˆØÐÜ�qÐ*¨IÓ6ò 	TˆAØˆIÜ˜!˜i™-Ð)9Ó:ˆGÜÐ4°YÑ?À$×BTÑBTÑTÓUˆLÜÐ2°7Ñ;¸d×>PÑ>PÑPÓQˆJØ×!Ñ! <°Ð"<Ô=Ü!$Ð%7¸ÀlÑ9RÓ!SÑð	Tð ˆØ(6ò 	0Ñ$ˆL˜*Ø˜L¨Ð4ˆGÜŸV™VØØÐ'¨'¯-©-¸Ñ*:Ñ:Ð;Ð=ØØ !ô	ˆNð ×Ñ Õ/ð	0ô —z‘z ,Ó/ˆØÐ2Ð2Ð2r0   Úfeaturesc           	      óø  — |D �cg c]  }|j                   ‘Œ }}g g }}t        |«      D �]Þ  \  }}t        |j                   «      dk(  r\t        g t	        |Ž ¢d   «      ||   d   z
  }t        j                  ||   d d t
        j                  ¬«      }	dd|fdf}
|
d   |
d   f}nq|j                  dd«      }t        g t	        |Ž ¢d   «      ||   d   z
  }t        j                  ||   t
        j                  ¬«      j                  dd«      }	dd|ffx}
}t        j                  ||
d| j                  ¬	«      }t        j                  |	|d| j                  ¬	«      }	|r‰t        g t	        |Ž ¢d   «      }t        j                  |t        j                  d|| j                  g«      gd¬
«      }t        j                  |	t        j                  d|g|	j                  ¬«      gd¬
«      }	|j                  |«       |j                  |	«       �Œá t        j                  |d¬
«      j!                  t
        j"                  «      }t        j                  |d¬
«      j!                  t
        j                  «      }||fS c c}w )Nr   r    r   )Údtype)r   r   r   r3   ra   rb   )Úaxis)re   Ú	enumeraterd   rj   Úzipr8   ÚonesÚint64Úreshaperk   r   ÚconcatenateÚzerosr   r|   r:   ÚastypeÚfloat32)r,   rz   Úadd_zero_lineÚeach_featureÚfeatures_shapesÚattention_masksÚpadded_featuresrq   Úfeatures_pad_valueÚattention_maskÚfeature_paddingÚattention_mask_paddingÚeach_padded_featureÚzero_array_lens                 r/   Ú_padzPop2PianoFeatureExtractor._padë   sp  € ØBJÖK°,˜<×-Ó-ÐKˆÐKØ+-¨r˜ˆÜ(¨Ó2ó !	3‰OˆAˆ|ä�<×%Ñ%Ó&¨!Ò+Ü%(Ð)A¬3°Ð+@Ð)AÀ!Ñ)DÓ%EÈÐXYÑHZÐ[\ÑH]Ñ%]Ð"Ü!#§¡¨¸Ñ);¸B¸QÐ)?ÄrÇxÁxÔ!P�Ø#)¨AÐ/AÐ+BÀFÐ"K�Ø*9¸!Ñ*<¸oÈaÑ>PÐ)QÑ&ð  ,×3Ñ3°A°rÓ:�Ü%(Ð)A¬3°Ð+@Ð)AÀ!Ñ)DÓ%EÈÐXYÑHZÐ[\ÑH]Ñ%]Ð"Ü!#§¡¨¸Ñ);Ä2Ç8Á8Ô!L×!TÑ!TÐUVÐXZÓ![�Ø<BÀQÐHZÐD[Ð;\Ð\�Ð"8ä"$§&¡&¨°È
Ðdh×dvÑdvÔ"wÐÜŸV™VØÐ 6¸
ÐTX×TfÑTfôˆNñ ä!$Ð%=¤s¨OÐ'<Ð%=¸aÑ%@Ó!A�ô ')§n¡nØ(¬"¯(©(°A°~Àt×GXÑGXÐ3YÓ*ZÐ[Ðbcô'Ð#ô "$§¡Ø#¤R§X¡X¨q°.Ð.AÈ×I]ÑI]Ô%^Ð_Ðfgô"�ð ×"Ñ"Ð#6Ô7Ø×"Ñ" >Ö2ðC!	3ôF Ÿ.™.¨¸qÔA×HÑHÌÏÉÓTˆÜŸ.™.¨¸qÔA×HÑHÌÏÉÓRˆà Ð/Ð/ùòQ Ls   …I7ÚinputsÚ
is_batchedÚreturn_attention_maskÚreturn_tensorsc                 ó  — i }|j                  «       D ]T  \  }}|dk(  r$| j                  |d¬«      \  }}	|||<   |sŒ)|	|d<   Œ/| j                  |d¬«      \  }}	|||<   |sŒM|	|d|› �<   ŒV |s|s|d   dd…d	f   |d<   t        ||¬
«      }
|
S )a—  
        Pads the inputs to same length and returns attention_mask.

        Args:
            inputs (`BatchFeature`):
                Processed audio features.
            is_batched (`bool`):
                Whether inputs are batched or not.
            return_attention_mask (`bool`):
                Whether to return attention mask or not.
            return_tensors (`str` or [`~utils.TensorType`], *optional*):
                If set, will return tensors instead of list of python integers. Acceptable values are:
                - `'pt'`: Return PyTorch `torch.Tensor` objects.
                - `'np'`: Return Numpy `np.ndarray` objects.
                If nothing is specified, it will return list of `np.ndarray` arrays.
        Return:
            `BatchFeature` with attention_mask, attention_mask_beatsteps and attention_mask_extrapolated_beatstep added
            to it:
            - **attention_mask** numpy.ndarray of shape `(batch_size, max_input_features_seq_length)` --
                Example :
                    1, 1, 1, 0, 0 (audio 1, also here it is padded to max length of 5 thats why there are 2 zeros at
                    the end indicating they are padded)

                    0, 0, 0, 0, 0 (zero pad to seperate audio 1 and 2)

                    1, 1, 1, 1, 1 (audio 2)

                    0, 0, 0, 0, 0 (zero pad to seperate audio 2 and 3)

                    1, 1, 1, 1, 1 (audio 3)
            - **attention_mask_beatsteps** numpy.ndarray of shape `(batch_size, max_beatsteps_seq_length)`
            - **attention_mask_extrapolated_beatstep** numpy.ndarray of shape `(batch_size,
              max_extrapolated_beatstep_seq_length)`
        r   T)r‡   r�   FÚattention_mask_Nr3   .)Útensor_type)Úitemsr’   r
   )r,   r“   r”   r•   r–   Úprocessed_features_dictÚfeature_nameÚfeature_valueÚpadded_feature_valuesr�   Úoutputss              r/   rk   zPop2PianoFeatureExtractor.pad  sÚ   € ðT #%ÐØ+1¯<©<«>ò 
	_Ñ'ˆL˜-ØÐ/Ò/Ø8<¿	¹	À-Ð_c¸	Ó8dÑ5Ð% ~Ø8MÐ'¨Ñ5Ú(Ø@NÐ+Ð,<Ò=à8<¿	¹	À-Ð_d¸	Ó8eÑ5Ð% ~Ø8MÐ'¨Ñ5Ú(ØP^Ð+¨o¸l¸^Ð,LÒMð
	_ñ Ñ"7Ø8OÐP`Ñ8aÐbeÐceÐbeÐgjÐbjÑ8kÐ#Ð$4Ñ5äÐ6ÀNÔSˆàˆr0   ÚresampleÚreturnc                 ó°  — t        | dg«       t        t        |t        t        f«      xr( t        |d   t
        j                  t        t        f«      «      }|r&t        |t        «      st        d|› d�«      ‚|€dn|}n|g}|g}|€dn|}g g g }}
}	t        ||«      D �]‘  \  }}| j                  |¬«      \  }}}}}| j                  ||d	¬
«      }| j                  |k7  rb| j                  �V|r.t        j                  j                  ||| j                  d¬«      }n&t        j                   d| j                  › d|› d�«       | j                  }t#        |d   |z  «      }t#        |d   |z  «      }| j%                  ||| ||d   z
  «      \  }}| j'                  |j)                  t
        j*                  «      «      }t        j,                  t        j.                  |dd¬«      «      }t        j0                  |d«      }|	j3                  |«       |
j3                  |«       |j3                  |«       �Œ” t5        |	|
|dœ«      }| j7                  ||||¬«      }|S )aú  
        Main method to featurize and prepare for the model.

        Args:
            audio (`np.ndarray`, `List`):
                The audio or batch of audio to be processed. Each audio can be a numpy array, a list of float values, a
                list of numpy arrays or a list of list of float values.
            sampling_rate (`int`):
                The sampling rate at which the `audio` input was sampled. It is strongly recommended to pass
                `sampling_rate` at the forward call to prevent silent errors.
            steps_per_beat (`int`, *optional*, defaults to 2):
                This is used in interpolating `beat_times`.
            resample (`bool`, *optional*, defaults to `True`):
                Determines whether to resample the audio to `sampling_rate` or not before processing. Must be True
                during inference.
            return_attention_mask (`bool` *optional*, defaults to `False`):
                Denotes if attention_mask for input_features, beatsteps and extrapolated_beatstep will be given as
                output or not. Automatically set to True for batched inputs.
            return_tensors (`str` or [`~utils.TensorType`], *optional*):
                If set, will return tensors instead of list of python integers. Acceptable values are:
                - `'pt'`: Return PyTorch `torch.Tensor` objects.
                - `'np'`: Return Numpy `np.ndarray` objects.
                If nothing is specified, it will return list of `np.ndarray` arrays.
        Úlibrosar   zwPlease give sampling_rate of each audio separately when you are passing multiple raw_audios at the same time. Received z), expected [audio_1_sr, ..., audio_n_sr].NTF)r?   r    r`   Úkaiser_best)Úorig_srÚ	target_srÚres_typezmThe sampling_rate of the provided audio is different from the target sampling_rate of the Feature Extractor, z vs zp. In these cases it is recommended to use `resample=True` in the `__call__` method to get the optimal behaviour.r3   g�íµ ÷Æ°>)Úa_minÚa_max)r   r3   éþÿÿÿr   )r”   r•   r–   )r   ÚboolÚ
isinstanceÚlistÚtupler8   Úndarrayrf   r   rL   r[   r   r£   Úcorer    ÚwarningsÚwarnri   ry   r>   r…   r†   ÚlogÚclipÚ	transposer:   r
   rk   )r,   r?   r   rM   r    r•   r–   r-   r”   Úbatch_input_featuresÚbatch_beatstepsÚbatch_ext_beatstepÚsingle_raw_audioÚsingle_sampling_raterG   rH   rI   rJ   rK   r   rt   ru   r   r   r<   Úlog_mel_specsÚoutputs                              r/   Ú__call__z"Pop2PianoFeatureExtractor.__call__V  s©  € ôF 	˜$  Ô,Üœ* U¬T´5¨MÓ:Òn¼zÈ%ÐPQÉ(ÔUW×U_ÑU_ÔafÔhlÐTmÓ?nÓoˆ
Ùä˜m¬TÔ2Ü ð Ø -˜Ð.WðYóð ð -BÐ,I¡DÐOdÑ!à�GˆEØ*˜OˆMØ-BÐ-J¡EÐPeÐ!àDFÈÈBÐ/A˜oÐÜ69¸%ÀÓ6Oó (	=Ñ2ÐÐ2ØNR×NaÑNaØ&ð Obó OÑKˆC�˜Z¨Ð4Kð ×3Ñ3¸zÐZhÐstÐ3ÓuˆIà×!Ñ!Ð%9Ò9¸d×>PÑ>PÐ>\Ùä'.§|¡|×'<Ñ'<Ø(Ø 4Ø"&×"4Ñ"4Ø!.ð	 (=ó (Ñ$ô —M‘Mð5Ø59×5GÑ5GÐ4HÈÐMaÐLbð c5ð6ôð $(×#5Ñ#5Ð Ü˜y¨™|Ð.BÑBÓCˆLÜ˜Y r™]Ð-AÑAÓBˆJà48×4GÑ4GØ  ¨jÐ9¸9ÀyÐQRÁ|Ñ;Só5Ñ1ˆNÐ1ð ×,Ñ,¨^×-BÑ-BÄ2Ç:Á:Ó-NÓOˆIô ŸF™F¤2§7¡7¨9¸DÈÔ#MÓNˆMäŸ\™\¨-¸ÓEˆNà ×'Ñ'¨Ô7Ø×"Ñ" 9Ô-Ø×%Ñ%Ð&;Ö<ðQ(	=ôT à"6Ø,Ø);ñó
ˆð —‘ØØ!Ø"7Ø)ð	 ó 
ˆð ˆr0   )i"V  r   i   i   g      $@i   r   )T)N)r   TFN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Úmodel_input_namesri   r*   r)   r8   r¯   r>   rL   Únumpyr[   ry   r’   r
   r«   r   r   Ústrr   rk   r   r½   Ú__classcell__)r.   s   @r/   r   r   2   sÖ  ø„ ñò: QÐð #ØØØØ#ØØñ 
àð 
ð ð 
ð ð	 
ð
 ð 
ð ð 
ð ð 
ð õ 
ðD¨¯
©
ó ð2O B§J¡Jó Oð ØŸ-™-ðØ9>¿¹ðØRW×R_ÑR_óð<.3 B§J¡Jð .3¸"¿*¹*ó .3ñ`)0˜RŸZ™Zó )0ð` <@ñ>àð>ð ð>ð  $ð	>ð
 !  s¨J Ñ!7Ñ8ó>ðH  Ø#'Ø05Ø;?ñlà�R—Z‘Z  e¡¨d°2·:±:Ñ.>ÀÀTÈ%Á[Ñ@QÐQÑRðlð ˜S $ s¡)˜^Ñ,ðlð ð	lð
 ˜4‘.ðlð  (¨™~ðlð !  s¨J Ñ!7Ñ8ðlð 
÷lr0   r   )rÁ   r±   Útypingr   r   r   rÃ   r8   Úaudio_utilsr   r   Ú!feature_extraction_sequence_utilsr	   Úfeature_extraction_utilsr
   Úutilsr   r   r   r   r   r   rA   Úessentia.standardr£   rP   Ú
get_loggerr¾   Úloggerr   Ú__all__r'   r0   r/   ú<module>rÏ      sz   ðñ ,ã ß (Ñ (ã Û ç 7Ý IÝ 4÷÷ ñ ÔÛÛáÔÛáÔÛð 
ˆ×	Ñ	˜HÓ	%€ôPÐ 8ô Pðf 'Ð
'�r0   