a
    d&                     @   s   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	 ddl
mZmZ e rZddlmZ e	eZeeejdd	d
ZeeG dd deZdS )    N)Union   )add_end_docstringsis_torch_availablelogging   )PIPELINE_INIT_ARGSPipeline)&MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING)bpayloadsampling_ratereturnc           
      C   s   | }d}d}dddd|d|d|d	d
ddg}zt j|t jt jd}W n ty^   tdY n0 || }|d }t|tj}	|	j	d dkrtd|	S )z?
    Helper function to read an audio file through ffmpeg.
    1Zf32leZ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npZ
frombufferfloat32shape)
r   r   aracZformat_for_conversionZffmpeg_commandZffmpeg_processZoutput_stream	out_bytesaudio r   t/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/transformers/pipelines/audio_classification.pyffmpeg_read   s6    
r!   c                       sb   e Zd ZdZ fddZeejee	f d fddZ
ddd	Zd
d Zdd ZdddZ  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                    sD   d|d< t  j|i | | jdkr6td| j d| t d S )N   top_kptzThe z is only available in PyTorch.)super__init__Z	frameworkr   	__class__Zcheck_model_typer
   )selfargskwargsr(   r   r    r'   ]   s
    
z$AudioClassificationPipeline.__init__)inputsc                    s   t  j|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`):
                The inputs is either a raw waveform (`np.ndarray` of shape (n, ) of type `np.float32` or `np.float64`)
                at the correct sampling rate (no further check will be done) or a `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. If *inputs* is `bytes` it is supposed to be the
                content of an audio file and is interpreted by *ffmpeg* in the same way.
            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.

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

            - **label** (`str`) -- The label predicted.
            - **score** (`float`) -- The corresponding probability.
        )r&   __call__)r)   r-   r+   r,   r   r    r.   g   s    z$AudioClassificationPipeline.__call__Nc                 K   s6   i }|d ur,|| j jjkr$| j jj}||d< i i |fS )Nr$   )modelconfigZ
num_labels)r)   r$   r+   Zpostprocess_paramsr   r   r    _sanitize_parameters   s    
z0AudioClassificationPipeline._sanitize_parametersc                 C   s   t |tr^|ds|dr,t|j}n2t|d}| }W d    n1 sT0    Y  t |trvt	|| j
j}t |tjstdt|jdkrtd| j
|| j
jdd}|S )	Nzhttp://zhttps://rbz"We expect a numpy ndarray as inputr   zMWe expect a single channel audio input for AutomaticSpeechRecognitionPipeliner%   )r   Zreturn_tensors)
isinstancestr
startswithrequestsgetcontentopenreadbytesr!   Zfeature_extractorr   r   ndarrayr   lenr   )r)   r-   f	processedr   r   r    
preprocess   s    
&

z&AudioClassificationPipeline.preprocessc                 C   s   | j f i |}|S )N)r/   )r)   Zmodel_inputsmodel_outputsr   r   r    _forward   s    z$AudioClassificationPipeline._forwardr#   c                    sJ   |j d d}||\}}| }| } fddt||D }|S )Nr   c                    s$   g | ]\}}| j jj| d qS ))scorelabel)r/   r0   Zid2label).0rD   Z_idr)   r   r    
<listcomp>       z;AudioClassificationPipeline.postprocess.<locals>.<listcomp>)ZlogitsZsoftmaxZtopktolistzip)r)   rA   r$   ZprobsZscoresidslabelsr   rG   r    postprocess   s    z'AudioClassificationPipeline.postprocess)N)r#   )__name__
__module____qualname____doc__r'   r   r   r<   r;   r4   r.   r1   r@   rB   rN   __classcell__r   r   r,   r    r"   B   s   
	r"   )r   typingr   numpyr   r6   utilsr   r   r   baser   r	   Zmodels.auto.modeling_autor
   Z
get_loggerrO   loggerr;   intarrayr!   r"   r   r   r   r    <module>   s   
$