Ë
    îÍ:j´+  ã                   óø   — d dl Z d dlmZmZ d dlZd dlZddlmZ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)ÚAnyÚUnioné   )Úadd_end_docstringsÚis_torch_availableÚis_torchaudio_availableÚis_torchcodec_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
             ú€/home/mcse/projects/srt_converter/srt-converter-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            	       ó˜   ‡ — e Zd ZdZdZdZdZdZˆ fd„Zde	e
j                  eeef   dedee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).
    FTc                 óÎ   •— 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Úkwargsr7   s      €r+   r5   z$AudioClassificationPipeline.__init__b   su   ø€ à�fÑ ¨¡Ð!8Ø"ˆF�7ŠOØ˜FÑ"ØˆF�7‰OÜ‰Ñ˜$Ð) &Ò)à�>‰>˜TÒ!Ü˜t D§N¡NÐ#3Ð3QÐRÓSÐSà×ÑÔJÕKó    Úinputsr;   r   c                 ó$   •— 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.
        )r4   Ú__call__)r9   r=   r;   r7   s      €r+   r?   z$AudioClassificationPipeline.__call__o   s   ø€ ôD ‰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 )Nr1   )ÚsoftmaxÚsigmoidÚnonez'Invalid value for `function_to_apply`: z2. Valid options are ['softmax', 'sigmoid', 'none']Úfunction_to_applyrA   )ÚmodelÚconfigÚ
num_labelsr   )r9   r1   rD   r;   Ú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        «       r8dd l}t        ||j                  «      r|j                  «       j!                  «       }t#        «       rSdd l}dd l}t        ||j&                  j(                  «      r+|j+                  «       }|j,                  }||j.                  dœ}t        |t0        «      �r|j3                  «       }d|v rd|v sd|v st5        d	«      ‚|j7                  dd «      }|€$|j7                  d
d «       |j7                  dd «      }|j7                  d«      }|}|| j                  j                  k7  r€dd l}t9        «       rddlm}	 nt?        d«      ‚|	jA                  t        |tB        jD                  «      r|jG                  |«      n||| j                  j                  «      j!                  «       }t        |tB        jD                  «      stI        d«      ‚tK        |jL                  «      dk7  rt5        d«      ‚| j                  || j                  j                  d¬«      }
| jN                  �|
jQ                  | jN                  ¬«      }
|
S # 1 sw Y   �Œ�xY w)Nzhttp://zhttps://Úrbr   )Úarrayr   r   ÚrawrL   zôWhen passing a dictionary to AudioClassificationPipeline, the dict needs to contain a "raw" key containing the numpy array or torch tensor representing the audio and a "sampling_rate" key, containing the sampling_rate associated with that arrayÚpath)Ú
functionalz›torchaudio is required to resample audio samples in AudioClassificationPipeline. The torchaudio package can be installed through: `pip install torchaudio`.z2We expect a numpy ndarray or torch tensor as inputr   zFWe expect a single channel audio input for AudioClassificationPipeliner3   )r   Úreturn_tensors)Údtype))Ú
isinstanceÚstrÚ
startswithÚrequestsÚgetÚcontentÚopenÚreadÚbytesr,   Úfeature_extractorr   r   ÚtorchÚTensorÚcpuÚnumpyr	   Ú
torchcodecÚdecodersÚAudioDecoderÚget_all_samplesÚdataÚsample_rateÚdictÚcopyr   Úpopr   Ú
torchaudiorO   ÚImportErrorÚresampler   ÚndarrayÚ
from_numpyÚ	TypeErrorÚlenr"   rQ   Úto)r9   r=   Úfr\   r`   Ú_audio_samplesÚ_arrayÚ_inputsÚin_sampling_rateÚ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äÔÛä˜& %§,¡,Ô/ØŸ™›×+Ñ+Ó-�ä"Ô$ÛÛä˜& *×"5Ñ"5×"BÑ"BÔCØ!'×!7Ñ!7Ó!9�Ø'×,Ñ,�Ø#)¸N×<VÑ<VÑW�ä�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óð ð
 Ÿ™Ü0:¸6Ä2Ç:Á:Ô0N�E×$Ñ$ VÔ,ÐTZØ$Ø×*Ñ*×8Ñ8ó÷ ‘%“'ð	 ô ˜&¤"§*¡*Ô-ÜÐPÓQÐQÜˆv�|‰|Ó Ò!ÜÐeÓfÐfà×*Ñ*Ø $×"8Ñ"8×"FÑ"FÐW[ð +ó 
ˆ	ð �:‰:Ð!Ø!Ÿ™¨4¯:©:˜Ó6ˆIØÐ÷E&ñ &ús   ÁK=Ë=Lc                 ó*   —  | j                   di |¤Ž}|S )N© )rE   )r9   Ú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 )NrA   r   éÿÿÿÿrB   )ÚscoreÚlabel)	ÚlogitsrA   rB   ÚtopkÚtolistÚziprE   rF   Úid2label)
r9   r|   r1   rD   ÚprobsÚscoresÚidsr€   Ú_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)r2   rA   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú_load_processorÚ_load_image_processorÚ_load_feature_extractorÚ_load_tokenizerr5   r   r   rl   rZ   rS   rf   r   Úlistr?   rI   rx   r}   rŒ   Ú__classcell__)r7   s   @r+   r/   r/   B   s|   ø„ ñð2 €OØ!ÐØ"ÐØ€OôLð"2˜u R§Z¡Z°¸¸TÐ%AÑBð "2Ècð "2ÐVZÐ[_Ð`cÐehÐ`hÑ[iÑVjõ "2óH*ò,IòV÷r<   r/   )r   Útypingr   r   r_   r   rU   Úutilsr   r   r   r	   r
   Úbaser   r   Úmodels.auto.modeling_autor   Ú
get_loggerr�   ÚloggerrZ   Úintrl   r,   r/   rz   r<   r+   ú<module>rž      s‚   ðó ß ã Û ç uÕ uß 4ñ ÔÝXà	ˆ×	Ñ	˜HÓ	%€ð!˜%ð !°ð !¸¿
¹
ó !ñH Ñ,À4ÔHÓIôC (ó Có JñCr<   