o
    %ݫij                  
   @   s  d Z ddlZddlZddlmZ ddlZddlZddlmZ ddl	m
Z ddl	mZ ddlmZ ddlmZmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZmZ ddlmZ ddl m!Z! ee"Z#dddi dddddej$f
defddZ%G dd dej&j'Z(G dd dZ)dS )aK  Defines interfaces for simple inference with pretrained models

Authors:
 * Aku Rouhe 2021
 * Peter Plantinga 2021
 * Loren Lugosch 2020
 * Mirco Ravanelli 2020
 * Titouan Parcollet 2021
 * Abdel Heba 2021
 * Andreas Nautsch 2022, 2023
 * Pooneh Mousavi 2023
 * Sylvain de Langen 2023
 * Adel Moumen 2023
 * Pradnya Kandarkar 2023
    N)SimpleNamespace)load_hyperpyyaml)DataParallel)SyncBatchNorm)DistributedDataParallel)PaddedBatch
PaddedData)AudioNormalizer)DataPipeline)
split_path)run_on_main)LocalStrategyfetch)
get_logger)import_from_pathhyperparams.yaml	custom.pyCustomInterfaceTFlocal_strategyc                 K   s   t || |dd|d|	|
d	}t || |dd|d|	|
d	}tjt|j t|dd}t|||}W d   n1 s:w   Y  ||d< |d }|| t	|j
| ||
dd	 |sr|  t|}t||}|d|d
 |d|S dS )a	  Fetch and load an interface from an outside source

    The source can be a location on the filesystem or online/huggingface

    The pymodule file should contain a class with the given classname. An
    instance of that class is returned. The idea is to have a custom Pretrained
    subclass in the file. The pymodule file is also added to the python path
    before the Hyperparams YAML file is loaded, so it can contain any custom
    implementations that are needed.

    The hyperparams file should contain a "modules" key, which is a
    dictionary of torch modules used for computation.

    The hyperparams file should contain a "pretrainer" key, which is a
    speechbrain.utils.parameter_transfer.Pretrainer

    Arguments
    ---------
    source : str or Path or FetchSource
        The location to use for finding the model. See
        ``speechbrain.utils.fetching.fetch`` for details.
    hparams_file : str
        The name of the hyperparameters file to use for constructing
        the modules necessary for inference. Must contain two keys:
        "modules" and "pretrainer", as described.
    pymodule_file : str
        The name of the Python file that should be fetched.
    classname : str
        The name of the Class, of which an instance is created and returned
    overrides : dict
        Any changes to make to the hparams file when it is loaded.
    overrides_must_match : bool
        Whether an error will be thrown when an override does not match
        a corresponding key in the yaml_stream.
    savedir : str or Path
        Where to put the pretraining material. If not given, just use cache.
    use_auth_token : bool (default: False)
        If true Huggingface's auth_token will be used to load private models from the HuggingFace Hub,
        default is False because the majority of models are public.
    download_only : bool (default: False)
        If true, class and instance creation is skipped.
    huggingface_cache_dir : str
        Path to HuggingFace cache; if None -> "~/.cache/huggingface" (default: None)
    local_strategy : speechbrain.utils.fetching.LocalStrategy
        The fetching strategy to use, which controls the behavior of remote file
        fetching with regards to symlinking and copying.
        See :func:`speechbrain.utils.fetching.fetch` for further details.
    **kwargs : dict
        Arguments to forward to class constructor.

    Returns
    -------
    object
        An instance of a class with the given classname from the given pymodule file.
    FN	filenamesourcesavedir	overwritesave_filenameuse_auth_tokenrevisionhuggingface_cache_dirr   utf-8encodingr   
pretrainerdefault_sourcer   r   kwargsmodules)r&   hparams )r   syspathappendstrparentopenr   set_collect_inr   collect_filesload_collectedr   getattr)r   hparams_filepymodule_file	classname	overridesoverrides_must_matchr   r   download_onlyr   r   r%   hparams_local_pathpymodule_local_pathfinr'   r!   moduleclsr(   r(   T/home/ubuntu/.local/lib/python3.10/site-packages/speechbrain/inference/interfaces.pyforeign_class(   sT   E
	
r?   c                       s   e Zd ZdZg Zg Z	d fdd	Zdd Zddd	Zd
d Z	dd Z
dd Zeddi ddddddejf
defddZ  ZS )
Pretraineda  Takes a trained model and makes predictions on new data.

    This is a base class which handles some common boilerplate.
    It intentionally has an interface similar to ``Brain`` - these base
    classes handle similar things.

    Subclasses of Pretrained should implement the actual logic of how
    the pretrained system runs, and add methods with descriptive names
    (e.g. transcribe_file() for ASR).

    Pretrained is a torch.nn.Module so that methods like .to() or .eval() can
    work. Subclasses should provide a suitable forward() implementation: by
    convention, it should be a method that takes a batch of audio signals and
    runs the full model (as applicable).

    Arguments
    ---------
    modules : dict of str:torch.nn.Module pairs
        The Torch modules that make up the learned system. These can be treated
        in special ways (put on the right device, frozen, etc.). These are available
        as attributes under ``self.mods``, like self.mods.model(x)
    hparams : dict
        Each key:value pair should consist of a string key and a hyperparameter
        that is used within the overridden methods. These will
        be accessible via an ``hparams`` attribute, using "dot" notation:
        e.g., self.hparams.model(x).
    run_opts : dict
        Options parsed from command line. See ``speechbrain.parse_arguments()``.
        List that are supported here:
         * device
         * data_parallel_count
         * data_parallel_backend
         * distributed_launch
         * distributed_backend
         * jit
         * jit_module_keys
         * compule
         * compile_module_keys
         * compile_mode
         * compile_using_fullgraph
         * compile_using_dynamic_shape_tracing
    freeze_params : bool
        To freeze (requires_grad=False) parameters or not. Normally in inference
        you want to freeze the params. Also calls .eval() on all modules.
    NTc           
         s,  t    ddddddd dd dddd}| D ],\}}|d ur-||v r-t| |||  q|d ur>||v r>t| |||  qt| || qtj|| _| j D ]}|d ur]|	| j
 qQ| jri|d u ritd|d ur| jD ]}	|	|vr~td|	 d	qptdi || _| | |d
t | _d S )NcpuFncclzreduce-overhead)devicedata_parallel_countdata_parallel_backenddistributed_launchdistributed_backendjitjit_module_keyscompilecompile_module_keyscompile_modecompile_using_fullgraph#compile_using_dynamic_shape_tracingzNeed to provide hparams dict.zNeed hparams['z']audio_normalizerr(   )super__init__itemssetattrtorchnn
ModuleDictmodsvaluestorD   HPARAMS_NEEDED
ValueErrorr   r'   _prepare_modulesgetr	   rP   )
selfr&   r'   run_optsfreeze_paramsrun_opt_defaultsargdefaultr<   hp	__class__r(   r>   rR      sJ   



zPretrained.__init__c                 C   s<   |    |   |r| j  | j D ]}d|_qdS dS )zPrepare modules for computation, e.g. jit.

        Arguments
        ---------
        freeze_params : bool
            Whether to freeze the parameters and call ``eval()``.
        FN)_compile_wrap_distributedrX   eval
parametersrequires_grad)r_   ra   pr(   r(   r>   r]     s   

zPretrained._prepare_modulesc                 C   sL   t |\}}t|||tjd}tjt|dd\}}|| j}| 	||S )a  Load an audio file with this model's input spec

        When using a speech model, it is important to use the same type of data,
        as was used to train the model. This means for example using the same
        sampling rate and number of channels. It is, however, possible to
        convert a file from a higher sampling rate to a lower one (downsampling).
        Similarly, it is simple to downmix a stereo file to mono.
        The path can be a local path, a web url, or a link to a huggingface repo.
        )r   r   r   F)channels_first)
r   r   r   SYMLINK
torchaudioloadr,   rZ   rD   rP   )r_   r*   r   r   flsignalsrr(   r(   r>   
load_audio  s   
zPretrained.load_audioc                 C   sj  t td}|s| jdurtdt }| jr+| jdu r!t| j}n
t| j}td t }| j	rF| j
du r<t| j}n
t| j
}td ||B D ]}|| jvrYtd| dqJ|D ]?}ztj| j| | j| j| jd}W n ty } ztd	| d
|  W Y d}~q\d}~ww || j| j|< || q\|D ]}tj	| j| }|| j| j|< qdS )z;Compile requested modules with either JIT or TorchInductor.rK   Nz_'compile_module_keys' specified, but this install of PyTorch seems to be too old to support it.zy--compile and --compile_module_keys are both specified. Only modules specified in --compile_module_keys will be compiled.zm--jit and --jit_module_keys are both specified. Only modules specified in --jit_module_keys will be compiled.zmodule z% is not defined in your hparams file.)mode	fullgraphdynamic'zh' in 'compile_module_keys' failed to compile and will be skipped (may fallback onto JIT, if specified): )hasattrrU   rL   r\   setrK   rX   loggerwarningrI   rJ   rM   rN   rO   	ExceptionrZ   rD   discardscript)r_   compile_availablerL   rJ   namer<   er(   r(   r>   rh   3  sd   







zPretrained._compilec                 C   s   t d |   d S )Nz4'_compile_jit' is deprecated; use '_compile' instead)warningswarnrh   r_   r(   r(   r>   _compile_jitt  s   
zPretrained._compile_jitc                 C   s   | j s| jsdS | j r4| j D ]!\}}tdd | D r1t|}t|| j	gd}|| j|< qdS | j D ]+\}}tdd | D rd| j
dkrRt|}nt|dd t| j
D }|| j|< q9dS )	z5Wrap modules with distributed wrapper when requested.Nc                 s       | ]}|j V  qd S Nrl   .0rm   r(   r(   r>   	<genexpr>~      z/Pretrained._wrap_distributed.<locals>.<genexpr>)
device_idsc                 s   r   r   r   r   r(   r(   r>   r     r   rB   c                 S   s   g | ]}|qS r(   r(   )r   ir(   r(   r>   
<listcomp>  s    z0Pretrained._wrap_distributed.<locals>.<listcomp>)rG   rF   rX   rS   anyrk   r   convert_sync_batchnormDDPrD   rE   DPrange)r_   r   r<   r(   r(   r>   ri   x  s(   




zPretrained._wrap_distributedr   r   Fr   c                 K   s  t |||dd|||	|d	}zt |||dd|||	|d	}tjt|j W n ty4   |dkr1n Y nw t|dd}t|||
d}W d   n1 sMw   Y  ||d< |	d	d}|dur|
| t|j|||d
d |s|  | |d |fi |S dS | |d |fi |S )af  Fetch and load based from outside source based on HyperPyYAML file

        The source can be a location on the filesystem or online/huggingface

        You can use the pymodule_file to include any custom implementations
        that are needed: if that file exists, then its location is added to
        sys.path before Hyperparams YAML is loaded, so it can be referenced
        in the YAML.

        The hyperparams file should contain a "modules" key, which is a
        dictionary of torch modules used for computation.

        The hyperparams file should contain a "pretrainer" key, which is a
        speechbrain.utils.parameter_transfer.Pretrainer

        Arguments
        ---------
        source : str
            The location to use for finding the model. See
            ``speechbrain.utils.fetching.fetch`` for details.
        hparams_file : str
            The name of the hyperparameters file to use for constructing
            the modules necessary for inference. Must contain two keys:
            "modules" and "pretrainer", as described.
        pymodule_file : str
            A Python file can be fetched. This allows any custom
            implementations to be included. The file's location is added to
            sys.path before the hyperparams YAML file is loaded, so it can be
            referenced in YAML.
            This is optional, but has a default: "custom.py". If the default
            file is not found, this is simply ignored, but if you give a
            different filename, then this will raise in case the file is not
            found.
        overrides : dict
            Any changes to make to the hparams file when it is loaded.
        savedir : str or Path
            Where to put the pretraining material. If not given, just use cache.
        use_auth_token : bool (default: False)
            If true Huggingface's auth_token will be used to load private models from the HuggingFace Hub,
            default is False because the majority of models are public.
        revision : str
            The model revision corresponding to the HuggingFace Hub model revision.
            This is particularly useful if you wish to pin your code to a particular
            version of a model hosted at HuggingFace.
        download_only : bool (default: False)
            If true, class and instance creation is skipped.
        huggingface_cache_dir : str
            Path to HuggingFace cache; if None -> "~/.cache/huggingface" (default: None)
        overrides_must_match : bool
            Whether the overrides must match the parameters already in the file.
        local_strategy : LocalStrategy, optional
            Which strategy to use to deal with files locally. (default:
            `LocalStrategy.SYMLINK`)
        **kwargs : dict
            Arguments to forward to class constructor.

        Returns
        -------
        Instance of cls
        FNr   r   r   r   )r7   r   r!   r"   r$   r&   )r   r)   r*   r+   r,   r-   r\   r.   r   r^   r/   r   r0   r1   )r=   r   r3   r4   r6   r   r   r   r8   r   r7   r   r%   r9   r:   r;   r'   r!   r(   r(   r>   from_hparams  sf   L
	zPretrained.from_hparams)NNNTr   )__name__
__module____qualname____doc__r[   MODULES_NEEDEDrR   r]   ru   rh   r   ri   classmethodr   ro   r   __classcell__r(   r(   rf   r>   r@      s2    .8
Ar@   c                   @   s   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dd Zedd Zedd Zedd Zdd Zdd Zdd ZdS )EncodeDecodePipelineMixinzv
    A mixin for pretrained models that makes it possible to specify an encoding pipeline and a decoding pipeline
    c                 C   s`   |  | jj |  | jj t| j| jjd | jjd d| _t| jj| jjd | jd| _dS )z<
        Initializes the encode and decode pipeline
        stepsoutput_keys)static_data_keysdynamic_itemsr   N)_run_init_stepsr'   encode_pipelinedecode_pipeliner
   INPUT_STATIC_KEYSmodel_output_keysOUTPUT_KEYSr   r(   r(   r>   create_pipelines%  s   


z*EncodeDecodePipelineMixin.create_pipelinesc                 C   s>   | dg }|D ]}| d}|rt|std|  qdS )zEncode/decode pipelines may include initialization
        steps, such as filling text encoders with tokens. Calling
        this method will run them, if definedinitfuncz Invalid pipeline init definitionN)r^   callabler\   )r_   pipeline_definitionr   step	step_funcr(   r(   r>   r   6  s   
z)EncodeDecodePipelineMixin._run_init_stepsc                    s&   |r |}|S  fdd|D }|S )Nc                    s   g | ]} |qS r(   r(   )r   itempipeliner(   r>   r   E      z;EncodeDecodePipelineMixin._run_pipeline.<locals>.<listcomp>r(   )r_   r   inputbatchoutputr(   r   r>   _run_pipelineA  s
   z'EncodeDecodePipelineMixin._run_pipelinec                 C   s   | j r|S | |S r   )batch_inputs_itemize)r_   r   r(   r(   r>   _get_encode_pipeline_inputH  s   z4EncodeDecodePipelineMixin._get_encode_pipeline_inputc                 C   sJ   t | jdd }|}t|dkr|f}|rtt||}| js#| |}|S )Nr      )r2   r'   lendictzipbatch_outputsr   )r_   model_outputr   pipeline_inputr(   r(   r>   _get_decode_pipeline_inputK  s   
z4EncodeDecodePipelineMixin._get_decode_pipeline_inputc                    sB   t t| }| |  t|} fddt|D S )Nc                    s(   g | ] t t fd dD qS )c                    s   g | ]}|  qS r(   r(   )r   valueidxr(   r>   r   a  r   zAEncodeDecodePipelineMixin._itemize.<locals>.<listcomp>.<listcomp>)r   r   )r   keysrY   r   r>   r   `  s    z6EncodeDecodePipelineMixin._itemize.<locals>.<listcomp>)nextiterrY   r   r   r   )r_   r   
first_itembatch_lengthr(   r   r>   r   \  s   z"EncodeDecodePipelineMixin._itemizec                    s*   t  tr fddjjd D   S )a  
        Converts padded batches to dictionaries, leaves
        other data types as is

        Arguments
        ---------
        data: object
            a dictionary or a padded batch

        Returns
        -------
        results: dict
            the dictionary
        c                    s   i | ]	}|  |qS r(   )
_get_value)r   keydatar_   r(   r>   
<dictcomp>u  s    z5EncodeDecodePipelineMixin.to_dict.<locals>.<dictcomp>r   )
isinstancer   r'   r   )r_   r   r(   r   r>   to_dicte  s
   

z!EncodeDecodePipelineMixin.to_dictc                 C   s$   t ||}| jst|tr|j}|S )aC  
        Retrieves the value associated with the specified key, dereferencing
        .data where applicable

        Arguments
        ---------
        data: PaddedBatch
            a padded batch
        key: str
            the key

        Returns
        -------
        result: object
            the result
        )r2   input_use_padded_datar   r   r   )r_   r   r   r   r(   r(   r>   r   {  s   
z$EncodeDecodePipelineMixin._get_valuec                 C      | j jddS )z
        Determines whether the input pipeline
        operates on batches or individual examples
        (true means batched)

        Returns
        -------
        batch_inputs: bool
        r   Tr'   r   r^   r   r(   r(   r>   r        z&EncodeDecodePipelineMixin.batch_inputsc                 C   r   )z
        If turned on, raw PaddedData instances will be passed to
        the model. If turned off, only .data will be used

        Returns
        -------
        result: bool
            whether padded data is used as is
        use_padded_dataFr   r   r(   r(   r>   r     r   z/EncodeDecodePipelineMixin.input_use_padded_datac                 C   r   )z
        Determines whether the output pipeline
        operates on batches or individual examples
        (true means batched)

        Returns
        -------
        batch_outputs: bool
        r   T)r'   r   r^   r   r(   r(   r>   r     r   z'EncodeDecodePipelineMixin.batch_outputsc                 C   s    | j st| jdt}||}|S )N
collate_fn)r   r2   r'   r   )r_   r   r   r(   r(   r>   _collate  s   z"EncodeDecodePipelineMixin._collatec                 C   sH   |  |}| j| j|| jd}| |}t|dr|| j}| |S )z
        Encodes the inputs using the pipeline

        Arguments
        ---------
        input: dict
            the raw inputs

        Returns
        -------
        results: object

        r   r   r   rZ   )	r   r   r   r   r   rz   rZ   rD   r   )r_   r   r   model_inputr(   r(   r>   encode_input  s   



z&EncodeDecodePipelineMixin.encode_inputc                 C   s   |  |}| j| j|| jdS )z
        Decodes the raw model outputs

        Arguments
        ---------
        output: tuple
            raw model outputs

        Returns
        -------
        result: dict or list
            the output of the pipeline
        r   )r   r   r   r   )r_   r   r   r(   r(   r>   decode_output  s   
z'EncodeDecodePipelineMixin.decode_outputN)r   r   r   r   r   r   r   r   r   r   r   r   propertyr   r   r   r   r   r   r(   r(   r(   r>   r      s&    	


r   )*r   r)   r   typesr   rU   rp   hyperpyyamlr   torch.nnr   r   r   torch.nn.parallelr   r   speechbrain.dataio.batchr   r   speechbrain.dataio.preprocessr	   speechbrain.utils.data_pipeliner
   speechbrain.utils.data_utilsr   speechbrain.utils.distributedr   speechbrain.utils.fetchingr   r   speechbrain.utils.loggerr   speechbrain.utils.superpowersr   r   r|   ro   r?   rV   Moduler@   r   r(   r(   r(   r>   <module>   sJ    
y   