o
    )j+                     @   s   d dl Z d dlmZ d dlmZmZ d dlmZm	Z	m
Z
mZmZ d dlmZ d dlmZ d dlmZmZ d dlmZmZmZ d dlmZmZ d d	lmZmZmZ d d
lm Z  d dl!m"Z" d dl#m$Z$m%Z% e" Z&ed Z'G dd deZ(dS )    N)ABCabstractmethod)AnyDictListOptionalUnion)snapshot_download)Tasks)build_backbonebuild_model)can_load_by_mscheck_model_from_owner_grouptry_to_load_hf_model)Config
ConfigDict)DEFAULT_MODEL_REVISIONInvoke	ModelFile)verify_device)
get_logger)register_modelhub_reporegister_plugins_repo)ztorch.Tensorz	tf.Tensorc                   @   s   e Zd ZdZdd Zdeeef fddZ		d de	e d	e	e fd
dZ
edeeef fddZdeeef deeef fddZedd Zeedddfdede	e dedede	e f
ddZ		d deeejf deeee f de	e fddZdS )!ModelzBase model interface.
    c                 O   s2   || _ |dd}t| || _|dd| _d S )Ndevicegputrust_remote_codeF)	model_dirgetr   Z_device_namer   )selfr   argskwargsZdevice_name r"   b/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/modelscope/models/base/base_model.py__init__   s
   zModel.__init__returnc                 O   s   |  | j|i |S )N)postprocessforwardr   r    r!   r"   r"   r#   __call__$   s   zModel.__call__Ninfo_strr   c                 C   s(   |pd}t |ds| jsJ |dS dS )a"  Check trust_remote_code if the model needs to import extra libs

        Args:
            info_str(str): The info showed to user if trust_remote_code is `False`.
            model_dir(`Optional[str]`): The local model directory. If is a trusted model, check remote code will pass.
        zThis model requires `trust_remote_code` to be `True` because it needs to import extra libs or execute the code in the model repo, setting this to true means you trust the files in it.)r   N)r   r   )r   r*   r   r"   r"   r#   check_trust_remote_code'   s   	
zModel.check_trust_remote_codec                 O   s   dS )z
        Run the forward pass for a model.

        Returns:
            Dict[str, Any]: output from the model forward pass
        Nr"   r(   r"   r"   r#   r'   7   s   zModel.forwardinputsc                 K   s   |S )a$   Model specific postprocess and convert model output to
        standard model outputs.

        Args:
            inputs:  input data

        Return:
            dict of results:  a dict containing outputs of model, each
                output should have the standard output name.
        r"   )r   r,   r!   r"   r"   r#   r&   A   s   zModel.postprocessc                 K   s   | di |S )a   Define the instantiation method of a model,default method is by
            calling the constructor. Note that in the case of no loading model
            process in constructor of a task model, a load_model method is
            added, and thus this method is overloaded
        Nr"   r"   )clsr!   r"   r"   r#   _instantiateN   s   zModel._instantiateFmodel_name_or_pathrevisioncfg_dictr   r   c                 K   s  | d}|dur|d | tj}|dur|tj ntj}|dd}	t|r0|}
n|du r8tddtj|f }t||||	d}
t	
d|
  t|
tj}d}|dur_|}ntj|rjt|}t|d	d}d	|v ry|d	}t|d
t }t|drt|ds|j|_t|dd}t|tr|drd|dd  }|dd}|du rt|
||rd}d}|dv rt|
||fi |}|dur|dd}|du r|dur||}|S |du rtdtj d|
|_|d}|r|std|r	|r	t	 d t!|
|d i }|rd|i}t"| |# D ]	\}}|||< q |dur2||_$|t%j&u r@d|_'t(|}nt)|||d}t|drQ|j*|_*t|dsZ||_+|dd ||_,|
|_|S )a  Instantiate a model from local directory or remote model repo. Note
        that when loading from remote, the model revision can be specified.

        Args:
            model_name_or_path(str): A model dir or a model id to be loaded
            revision(str, `optional`): The revision used when the model_name_or_path is
                a model id of the remote hub. default `master`.
            cfg_dict(Config, `optional`): An optional model config. If provided, it will replace
                the config read out of the `model_name_or_path`
            device(str, `optional`): The device to load the model.
            trust_remote_code(bool, `optional`): Whether to trust and allow execution of remote code. Default is False.
            **kwargs:
                task(str, `optional`): The `Tasks` enumeration value to replace the task value
                    read out of config in the `model_name_or_path`. This is useful when the model to be loaded is not
                    equal to the model saved.
                    For example, load a `backbone` into a `text-classification` model.
                    Other kwargs will be directly fed into the `model` key, to replace the default configs.
                use_hf(bool, `optional`):
                    If set to True, it will initialize the model using AutoModel or AutoModelFor* from hf.
                    If set to False, the model is loaded using the modelscope mode.
                    If set to None, the loading mode will be automatically selected.
                ignore_file_pattern(List[str], `optional`):
                    This parameter is passed to snapshot_download
                device_map(str | Dict[str, str], `optional`):
                    This parameter is passed to AutoModel or AutoModelFor*
                torch_dtype(torch.dtype, `optional`):
                    This parameter is passed to AutoModel or AutoModelFor*
                config(PretrainedConfig, `optional`):
                    This parameter is passed to AutoModel or AutoModelFor*
        Returns:
            A model instance.

        Examples:
            >>> from modelscope.models import Model
            >>> Model.from_pretrained('damo/nlp_structbert_backbone_base_std', task='text-classification')
        Zmodel_prefetchedNignore_file_patternTz9Expecting model is pre-fetched locally, but is not found.z%s/%s)
user_agentr2   zinitialize model from taskmodel
model_typetyper   cuda   use_hfF>   TN
device_map`z` file not found.pluginsa  Detected plugins field in the model configuration file, but trust_remote_code=True was not explicitly set.
To prevent potential execution of malicious code, loading has been refused.
If you trust this model repository, please pass trust_remote_code=True to from_pretrained.zUse trust_remote_code=True. Will invoke codes or install plugins from remote model repo. Please make sure that you can trust the external codes.)Zallow_remoter   )	task_namedefault_argspipelinecfgr   )-r   popr   ZKEYZ
PRETRAINEDospexistsRuntimeErrorr	   loggerinfojoinr   ZCONFIGURATIONospathr   	from_filegetattrr   hasattrr6   r7   
isinstancestr
startswithr   r   toFileNotFoundErrorr   Zsafe_getwarningr   r   itemsr   r
   ZbackboneZinit_backboner   r   r@   rA   name)r-   r/   r0   r1   r   r   r!   Z
prefetchedZ
invoked_byr2   Zlocal_model_dirZconfiguration_pathrA   r>   Z	model_cfgr6   r:   r5   r;   r=   r?   kvr"   r"   r#   from_pretrainedW   s   
,







zModel.from_pretrainedtarget_foldersave_checkpoint_namesconfigc                 K   s   t d)a   save the pretrained model, its configuration and other related files to a directory,
            so that it can be re-loaded

        Args:
            target_folder (Union[str, os.PathLike]):
            Directory to which to save. Will be created if it doesn't exist.

            save_checkpoint_names (Union[str, List[str]]):
            The checkpoint names to be saved in the target_folder

            config (Optional[dict], optional):
            The config for the configuration.json, might not be identical with model.config
        z>save_pretrained method need to be implemented by the subclass.)NotImplementedError)r   rY   rZ   r[   r!   r"   r"   r#   save_pretrained   s   zModel.save_pretrained)NN)__name__
__module____qualname____doc__r$   r   rO   r   r)   r   r+   r   r'   r&   classmethodr.   r   r   boolrX   r   rI   PathLiker   dictr]   r"   r"   r"   r#   r      sT    
"	
 r   ))rI   Zos.pathrJ   rC   abcr   r   typingr   r   r   r   r   Z modelscope.hub.snapshot_downloadr	   Zmodelscope.metainfor
   Zmodelscope.models.builderr   r   Z modelscope.utils.automodel_utilsr   r   r   Zmodelscope.utils.configr   r   Zmodelscope.utils.constantr   r   r   Zmodelscope.utils.devicer   Zmodelscope.utils.loggerr   Zmodelscope.utils.pluginsr   r   rF   ZTensorr   r"   r"   r"   r#   <module>   s    