Ë
    T^(hÕ  ã                   ó¸   — d dl mZ d dl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mZ  e	j                  e«      Z e ed	d	¬
«      «       G d„ de«      «       Zy)é    )ÚUserDict)ÚUnionNé   )Úadd_end_docstringsÚloggingé   )Úffmpeg_read)ÚPipelineÚbuild_pipeline_init_argsT)Úhas_feature_extractorÚhas_tokenizerc                   ól   ‡ — e Zd ZdZˆ fd„Zdeej                  ee	f   fˆ fd„Z
d„ Zd	d„Zd„ Zd„ Zˆ xZS )
Ú#ZeroShotAudioClassificationPipelineaã  
    Zero shot audio classification pipeline using `ClapModel`. This pipeline predicts the class of an audio when you
    provide an audio and a set of `candidate_labels`.

    <Tip warning={true}>

    The default `hypothesis_template` is : `"This is a sound of {}."`. Make sure you update it for your usage.

    </Tip>

    Example:
    ```python
    >>> from transformers import pipeline
    >>> from datasets import load_dataset

    >>> dataset = load_dataset("ashraq/esc50")
    >>> audio = next(iter(dataset["train"]["audio"]))["array"]
    >>> classifier = pipeline(task="zero-shot-audio-classification", model="laion/clap-htsat-unfused")
    >>> classifier(audio, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"])
    [{'score': 0.9996, 'label': 'Sound of a dog'}, {'score': 0.0004, 'label': 'Sound of vaccum cleaner'}]
    ```


    Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) This audio
    classification pipeline can currently be loaded from [`pipeline`] using the following task identifier:
    `"zero-shot-audio-classification"`. See the list of available models on
    [huggingface.co/models](https://huggingface.co/models?filter=zero-shot-audio-classification).
    c                 ót   •— t        ‰| �  di |¤Ž | j                  dk7  rt        d| j                  › d�«      ‚y )NÚptzThe z is only available in PyTorch.© )ÚsuperÚ__init__Ú	frameworkÚ
ValueErrorÚ	__class__)ÚselfÚkwargsr   s     €ús/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/pipelines/zero_shot_audio_classification.pyr   z,ZeroShotAudioClassificationPipeline.__init__?   s>   ø€ Ü‰ÑÑ"˜6Ò"à�>‰>˜TÒ!Ü˜t D§N¡NÐ#3Ð3QÐRÓSÐSð "ó    Úaudiosc                 ó$   •— t        ‰| �  |fi |¤ŽS )a  
        Assign labels to the audio(s) passed as inputs.

        Args:
            audios (`str`, `List[str]`, `np.array` or `List[np.array]`):
                The pipeline handles three types of inputs:
                - A string containing a http link pointing to an audio
                - A string containing a local path to an audio
                - An audio loaded in numpy
            candidate_labels (`List[str]`):
                The candidate labels for this audio. They will be formatted using *hypothesis_template*.
            hypothesis_template (`str`, *optional*, defaults to `"This is a sound of {}"`):
                The format used in conjunction with *candidate_labels* to attempt the audio classification by
                replacing the placeholder with the candidate_labels. Pass "{}" if *candidate_labels* are
                already formatted.
        Return:
            A list of dictionaries containing one entry per proposed label. Each dictionary contains the
            following keys:
            - **label** (`str`) -- One of the suggested *candidate_labels*.
            - **score** (`float`) -- The score attributed by the model to that label. It is a value between
                0 and 1, computed as the `softmax` of `logits_per_audio`.
        )r   Ú__call__)r   r   r   r   s      €r   r   z,ZeroShotAudioClassificationPipeline.__call__F   s   ø€ ô. ‰wÑ Ñ1¨&Ñ1Ð1r   c                 ó@   — i }d|v r|d   |d<   d|v r|d   |d<   |i i fS )NÚcandidate_labelsÚhypothesis_templater   )r   r   Úpreprocess_paramss      r   Ú_sanitize_parametersz8ZeroShotAudioClassificationPipeline._sanitize_parameters_   sI   € ØÐØ Ñ'Ø4:Ð;MÑ4NÐÐ0Ñ1Ø  FÑ*Ø7=Ð>SÑ7TÐÐ3Ñ4à  " bÐ(Ð(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        j                  «      st        d«      ‚t        |j                   «      dk7  rt#        d«      ‚| j                  |g| j                  j                  d¬«      }| j$                  dk(  r|j'                  | j(                  «      }||d	<   |D �cg c]  }|j+                  |«      ‘Œ }}| j-                  || j$                  d
¬«      }|g|d<   |S # 1 sw Y   �ŒxY wc c}w )Nzhttp://zhttps://Úrbz"We expect a numpy ndarray as inputr   zNWe expect a single channel audio input for ZeroShotAudioClassificationPipeliner   )Úsampling_rateÚreturn_tensorsr    T)r'   ÚpaddingÚtext_inputs)Ú
isinstanceÚstrÚ
startswithÚrequestsÚgetÚcontentÚopenÚreadÚbytesr	   Úfeature_extractorr&   ÚnpÚndarrayÚ	TypeErrorÚlenÚshaper   r   ÚtoÚtorch_dtypeÚformatÚ	tokenizer)	r   Úaudior    r!   ÚfÚinputsÚxÚ	sequencesr)   s	            r   Ú
preprocessz.ZeroShotAudioClassificationPipeline.preprocessh   sj  € Ü�eœSÔ!Ø×Ñ 	Ô*¨e×.>Ñ.>¸zÔ.Jô !Ÿ™ UÓ+×3Ñ3‘ä˜% Ó&ð %¨!ØŸF™F›H�E÷%ô �eœUÔ#Ü  t×'=Ñ'=×'KÑ'KÓLˆEä˜%¤§¡Ô,ÜÐ@ÓAÐAÜˆu�{‰{Ó˜qÒ ÜÐmÓnÐnà×'Ñ'ØˆG 4×#9Ñ#9×#GÑ#GÐX\ð (ó 
ˆð �>‰>˜TÒ!Ø—Y‘Y˜t×/Ñ/Ó0ˆFØ%5ˆÐ!Ñ"Ø<LÖM°qÐ(×/Ñ/°Õ2ÐMˆ	ÐMØ—n‘n Y¸t¿~¹~ÐW[�nÓ\ˆØ!, ˆˆ}ÑØˆ÷)%ñ %üò" Ns   ÁFÅFÆFc                 óÒ   — |j                  d«      }|j                  d«      }t        |d   t        «      r|d   }n|d   d   } | j                  di |¤|¤Ž}||j                  dœ}|S )Nr    r)   r   )r    Úlogitsr   )Úpopr*   r   ÚmodelÚlogits_per_audio)r   Úmodel_inputsr    r)   ÚoutputsÚmodel_outputss         r   Ú_forwardz,ZeroShotAudioClassificationPipeline._forward…   s€   € Ø'×+Ñ+Ð,>Ó?ÐØ"×&Ñ& }Ó5ˆÜ�k !‘n¤hÔ/Ø% a™.‰Kð & a™.¨Ñ+ˆKà�$—*‘*Ñ;˜{Ð;¨lÑ;ˆð !1Ø×.Ñ.ñ
ˆð Ðr   c                 ó  — |j                  d«      }|d   d   }| j                  dk(  r#|j                  d¬«      }|j                  «       }nt	        d«      ‚t        t        ||«      d„ ¬«      D ��cg c]
  \  }}||d	œ‘Œ }}}|S c c}}w )
Nr    rD   r   r   )Údimz`tf` framework not supported.c                 ó   — | d    S )Nr   r   )r@   s    r   ú<lambda>zAZeroShotAudioClassificationPipeline.postprocess.<locals>.<lambda>¢   s   € Ð_`ÐabÑ_cÐ^c€ r   )Úkey)ÚscoreÚlabel)rE   r   ÚsoftmaxÚtolistr   ÚsortedÚzip)	r   rJ   r    rD   ÚprobsÚscoresrQ   Úcandidate_labelÚresults	            r   Úpostprocessz/ZeroShotAudioClassificationPipeline.postprocess–   sš   € Ø(×,Ñ,Ð-?Ó@ÐØ˜xÑ(¨Ñ+ˆà�>‰>˜TÒ!Ø—N‘N q�NÓ)ˆEØ—\‘\“^‰FäÐ<Ó=Ð=ô +1´°VÐ=MÓ1NÑTcÔ*d÷
á&��ð  oÓ6ð
ˆñ 
ð ˆùó	
s   Á2B)NzThis is a sound of {}.)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r4   r5   r2   r+   r   r#   rB   rK   r[   Ú__classcell__)r   s   @r   r   r       s>   ø„ ñô:Tð2˜u R§Z¡Z°¸Ð%;Ñ<õ 2ò2)óò:ö"r   r   )Úcollectionsr   Útypingr   Únumpyr4   r-   Úutilsr   r   Úaudio_classificationr	   Úbaser
   r   Ú
get_loggerr\   Úloggerr   r   r   r   ú<module>ri      sa   ðõ !Ý ã Û ÷õ .ß 4ð 
ˆ×	Ñ	˜HÓ	%€ñ Ñ,À4ÐW[Ô\Ó]ôC¨(ó Có ^ñCr   