Ë
    T^(h©(  ã                   óð   — d dl Z d dlmZ d dlZd dlZddlmZmZm	Z	m
Z
 ddlmZmZ  e«       rddlmZ  e
j                   e«      Zded	ed
ej*                  fd„Z e ed¬«      «       G d„ de«      «       Zy)é    N)ÚUnioné   )Úadd_end_docstringsÚis_torch_availableÚis_torchaudio_availableÚloggingé   )ÚPipelineÚbuild_pipeline_init_args)Ú,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMESÚbpayloadÚsampling_rateÚreturnc                 óz  — |› }d}d}dddd|d|d|d	d
ddg}	 t        j                  |t         j                  t         j                  ¬«      }|j                  | «      }|d   }t        j                  |t        j                  «      }	|	j                  d   dk(  rt	        d«      ‚|	S # t        $ r t	        d«      ‚w xY w)z?
    Helper function to read an audio file through ffmpeg.
    Ú1Úf32leÚffmpegz-izpipe:0z-acz-arz-fz-hide_bannerz	-loglevelÚquietzpipe:1)ÚstdinÚstdoutzFffmpeg was not found but is required to load audio files from filenamer   zMalformed soundfile)
Ú
subprocessÚPopenÚPIPEÚFileNotFoundErrorÚ
ValueErrorÚcommunicateÚnpÚ
frombufferÚfloat32Úshape)
r   r   ÚarÚacÚformat_for_conversionÚffmpeg_commandÚffmpeg_processÚoutput_streamÚ	out_bytesÚaudios
             úi/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/pipelines/audio_classification.pyÚffmpeg_readr*      sÙ   € ð ˆ?€BØ	€BØ#ÐàØØØØ
ØØ
ØØØØØØð€Nð cÜ#×)Ñ)¨.Ä
ÇÁÔXb×XgÑXgÔhˆð #×.Ñ.¨xÓ8€MØ˜aÑ €Iä�M‰M˜)¤R§Z¡ZÓ0€EØ‡{�{�1�~˜ÒÜÐ.Ó/Ð/Ø€Løô ò cÜÐaÓbÐbðcús   ˜4B% Â%B:T)Úhas_feature_extractorc                   ón   ‡ — e Zd ZdZˆ fd„Zdeej                  ee	f   fˆ fd„Z
d	d„Zd„ Zd„ Zd
d„Zˆ xZS )ÚAudioClassificationPipelinea  
    Audio classification pipeline using any `AutoModelForAudioClassification`. This pipeline predicts the class of a
    raw waveform or an audio file. In case of an audio file, ffmpeg should be installed to support multiple audio
    formats.

    Example:

    ```python
    >>> from transformers import pipeline

    >>> classifier = pipeline(model="superb/wav2vec2-base-superb-ks")
    >>> classifier("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac")
    [{'score': 0.997, 'label': '_unknown_'}, {'score': 0.002, 'label': 'left'}, {'score': 0.0, 'label': 'yes'}, {'score': 0.0, 'label': 'down'}, {'score': 0.0, 'label': 'stop'}]
    ```

    Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)


    This pipeline can currently be loaded from [`pipeline`] using the following task identifier:
    `"audio-classification"`.

    See the list of available models on
    [huggingface.co/models](https://huggingface.co/models?filter=audio-classification).
    c                 óÎ   •— d|v r|d   €d |d<   n	d|vrd|d<   t        ‰| �  |i |¤Ž | j                  dk7  rt        d| j                  › d�«      ‚| j                  t        «       y )NÚtop_ké   ÚptzThe z is only available in PyTorch.)ÚsuperÚ__init__Ú	frameworkr   Ú	__class__Úcheck_model_typer   )ÚselfÚargsÚkwargsr5   s      €r)   r3   z$AudioClassificationPipeline.__init__]   su   ø€ à�fÑ ¨¡Ð!8Ø"ˆF�7ŠOØ˜FÑ"ØˆF�7‰OÜ‰Ñ˜$Ð) &Ò)à�>‰>˜TÒ!Ü˜t D§N¡NÐ#3Ð3QÐRÓSÐSà×ÑÔJÕKó    Úinputsc                 ó$   •— t        ‰| �  |fi |¤ŽS )a¨  
        Classify the sequence(s) given as inputs. See the [`AutomaticSpeechRecognitionPipeline`] documentation for more
        information.

        Args:
            inputs (`np.ndarray` or `bytes` or `str` or `dict`):
                The inputs is either :
                    - `str` that is the filename of the audio file, the file will be read at the correct sampling rate
                      to get the waveform using *ffmpeg*. This requires *ffmpeg* to be installed on the system.
                    - `bytes` it is supposed to be the content of an audio file and is interpreted by *ffmpeg* in the
                      same way.
                    - (`np.ndarray` of shape (n, ) of type `np.float32` or `np.float64`)
                        Raw audio at the correct sampling rate (no further check will be done)
                    - `dict` form can be used to pass raw audio sampled at arbitrary `sampling_rate` and let this
                      pipeline do the resampling. The dict must be either be in the format `{"sampling_rate": int,
                      "raw": np.array}`, or `{"sampling_rate": int, "array": np.array}`, where the key `"raw"` or
                      `"array"` is used to denote the raw audio waveform.
            top_k (`int`, *optional*, defaults to None):
                The number of top labels that will be returned by the pipeline. If the provided number is `None` or
                higher than the number of labels available in the model configuration, it will default to the number of
                labels.
            function_to_apply(`str`, *optional*, defaults to "softmax"):
                The function to apply to the model output. By default, the pipeline will apply the softmax function to
                the output of the model. Valid options: ["softmax", "sigmoid", "none"]. Note that passing Python's
                built-in `None` will default to "softmax", so you need to pass the string "none" to disable any
                post-processing.

        Return:
            A list of `dict` with the following keys:

            - **label** (`str`) -- The label predicted.
            - **score** (`float`) -- The corresponding probability.
        )r2   Ú__call__)r7   r;   r9   r5   s      €r)   r=   z$AudioClassificationPipeline.__call__j   s   ø€ ôL ‰wÑ Ñ1¨&Ñ1Ð1r:   c                 ó,  — i }|€$| j                   j                  j                  |d<   nH|| j                   j                  j                  kD  r | j                   j                  j                  }||d<   |�|dvrt        d|› d�«      ‚||d<   nd|d<   i i |fS )Nr/   )ÚsoftmaxÚsigmoidÚnonez'Invalid value for `function_to_apply`: z2. Valid options are ['softmax', 'sigmoid', 'none']Úfunction_to_applyr?   )ÚmodelÚconfigÚ
num_labelsr   )r7   r/   rB   r9   Úpostprocess_paramss        r)   Ú_sanitize_parametersz0AudioClassificationPipeline._sanitize_parameters’   s½   € ØÐð ˆ=Ø*.¯*©*×*;Ñ*;×*FÑ*FÐ˜wÒ'à�t—z‘z×(Ñ(×3Ñ3Ò3ØŸ
™
×)Ñ)×4Ñ4�Ø*/Ð˜wÑ'àÐ(Ø Ð(FÑFÜ Ø=Ð>OÐ=Pð QGð Góð ð 7HÐÐ2Ò3à6?ÐÐ2Ñ3Ø�2Ð)Ð)Ð)r:   c                 óœ  — t        |t        «      rg|j                  d«      s|j                  d«      r t        j                  |«      j
                  }n%t        |d«      5 }|j                  «       }d d d «       t        |t        «      r t        || j                  j                  «      }t        |t        «      rï|j                  «       }d|v rd|v sd|v st        d«      ‚|j                  dd «      }|€$|j                  dd «       |j                  dd «      }|j                  d«      }|}|| j                  j                  k7  rdd	d l}t#        «       rd	d
lm} nt)        d«      ‚|j+                  |j-                  |«      || j                  j                  «      j/                  «       }t        |t0        j2                  «      st5        d«      ‚t7        |j8                  «      dk7  rt        d«      ‚| j                  || j                  j                  d¬«      }| j:                  �|j=                  | j:                  ¬«      }|S # 1 sw Y   �ŒÓxY w)Nzhttp://zhttps://Úrbr   ÚrawÚarrayzäWhen passing a dictionary to AudioClassificationPipeline, the dict needs to contain a "raw" key containing the numpy array representing the audio and a "sampling_rate" key, containing the sampling_rate associated with that arrayÚpathr   )Ú
functionalz›torchaudio is required to resample audio samples in AudioClassificationPipeline. The torchaudio package can be installed through: `pip install torchaudio`.z"We expect a numpy ndarray as inputr	   zFWe expect a single channel audio input for AudioClassificationPipeliner1   )r   Úreturn_tensors)Údtype)Ú
isinstanceÚstrÚ
startswithÚrequestsÚgetÚcontentÚopenÚreadÚbytesr*   Úfeature_extractorr   ÚdictÚcopyr   ÚpopÚtorchr   Ú
torchaudiorM   ÚImportErrorÚresampleÚ
from_numpyÚnumpyr   ÚndarrayÚ	TypeErrorÚlenr    Útorch_dtypeÚto)r7   r;   ÚfÚ_inputsÚin_sampling_rater]   ÚFÚ	processeds           r)   Ú
preprocessz&AudioClassificationPipeline.preprocess¨   s  € Ü�fœcÔ"Ø× Ñ  Ô+¨v×/@Ñ/@ÀÔ/Lô "Ÿ™ fÓ-×5Ñ5‘ä˜& $Ó'ð &¨1ØŸV™V›X�F÷&ô �fœeÔ$Ü  ¨×)?Ñ)?×)MÑ)MÓNˆFä�fœdÔ#Ø—[‘[“]ˆFð $ vÑ-°5¸F±?ÀgÐQWÑFWÜ ðNóð ð —j‘j ¨Ó-ˆGØˆà—
‘
˜6 4Ô(Ø Ÿ*™* W¨dÓ3�Ø%Ÿz™z¨/Ó:ÐØˆFØ 4×#9Ñ#9×#GÑ#GÒGÛä*Ô,Þ:ä%ðeóð ð
 Ÿ™Ø×$Ñ$ VÓ,Ð.>À×@VÑ@V×@dÑ@dóç‘%“'ð ô ˜&¤"§*¡*Ô-ÜÐ@ÓAÐAÜˆv�|‰|Ó Ò!ÜÐeÓfÐfà×*Ñ*Ø $×"8Ñ"8×"FÑ"FÐW[ð +ó 
ˆ	ð ×ÑÐ'Ø!Ÿ™¨4×+;Ñ+;˜Ó<ˆIØÐ÷c&ñ &ús   ÁIÉIc                 ó*   —  | j                   di |¤Ž}|S )N© )rC   )r7   Úmodel_inputsÚmodel_outputss      r)   Ú_forwardz$AudioClassificationPipeline._forwardâ   s   € Ø"˜Ÿ
™
Ñ2 \Ñ2ˆØÐr:   c                 óª  — |dk(  r|j                   d   j                  d«      }n2|dk(  r|j                   d   j                  «       }n|j                   d   }|j                  |«      \  }}|j	                  «       }|j	                  «       }t        ||«      D ��cg c]+  \  }}|| j                  j                  j                  |   dœ‘Œ- }	}}|	S c c}}w )Nr?   r   éÿÿÿÿr@   )ÚscoreÚlabel)	Úlogitsr?   r@   ÚtopkÚtolistÚziprC   rD   Úid2label)
r7   rq   r/   rB   ÚprobsÚscoresÚidsru   Ú_idÚlabelss
             r)   Úpostprocessz'AudioClassificationPipeline.postprocessæ   sÆ   € Ø 	Ò)Ø!×(Ñ(¨Ñ+×3Ñ3°BÓ7‰EØ )Ò+Ø!×(Ñ(¨Ñ+×3Ñ3Ó5‰Eà!×(Ñ(¨Ñ+ˆEØ—j‘j Ó'‰ˆ�à—‘“ˆØ�j‰j‹lˆä_bÐciÐknÓ_o×pÑQ[ÐQVÐX[˜E¨D¯J©J×,=Ñ,=×,FÑ,FÀsÑ,KÓLÐpˆÑpàˆùó qs   Â0C)NN)r0   r?   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r3   r   r   rc   rX   rQ   r=   rG   rm   rr   r�   Ú__classcell__)r5   s   @r)   r-   r-   B   sA   ø„ ñô2Lð&2à�b—j‘j %¨Ð,Ñ-õ&2óP*ò,8òt÷r:   r-   )r   Útypingr   rb   r   rS   Úutilsr   r   r   r   Úbaser
   r   Úmodels.auto.modeling_autor   Ú
get_loggerr‚   ÚloggerrX   ÚintrK   r*   r-   ro   r:   r)   ú<module>rŽ      s‚   ðó Ý ã Û ç \Ó \ß 4ñ ÔÝXà	ˆ×	Ñ	˜HÓ	%€ð!˜%ð !°ð !¸¿¹ó !ñH Ñ,À4ÔHÓIôq (ó qó Jñqr:   