o
    ॵi<                     @   s  d dl Z d dlmZmZ d dlmZmZmZmZ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mZ d dlmZmZ d dlmZ d	d
lmZ e Zi ejej fej!ej"ej#fej#ej$ej%fej&ej$ej'fej'ej$ej(fej(ej$ej)fej)ej$ej*fej&ej$ej+fej&ej$ej,fej&ej$ej-fej&ej$ej.fej&ej$ej/fej&ej$ej0fej0ej$ej1fej2ej$ej3fej2ej$ej4fej2ej$ej5fej2i ej6ej%fej7ej8ej%fej9ej:ej%fej7ej;ej%fej<ej;ej=fej<ej>ej%fej&ej>ej(fej(ej?ej(fej@ejAej%fej&ejAej(fej(ejAejBfejCejAej*fej&ejAej,fej&ejAej-fej&ejAej.fej&ejAej/fej&ejAej1fej2i ejDejEfej2ejAej3fej2ejAej5fej2ejFejGfejGejFejHfejHejFejIfejIejJej%fej&ejJej(fej(ejJej*fej&ejJej,fej&ejJej-fej&ejJej.fej&ejKejEfejLejKej5fejLejKej1fejLejMej5fejLejNej5fejLejOejEfejLej3ej3fejLej3ej1fejLej3ejEfejLej*ej*fej&ej(ej(fej(ejPejPfejPejQejQfejRej0ej0fej0ejSejSfej7ejTejUfejVejWejUfejVejWejXfejVejYejYfejZiZ[G dd deZ\dS )    N)ABCabstractmethod)AnyCallableDictOptionalSequenceUnion)ModelsPreprocessors
TaskModels)Config
ConfigDict)DEFAULT_MODEL_REVISIONInvokeModeKeysTasks)read_configsnapshot_download)
get_logger   )build_preprocessorc                   @   s   e Zd ZdZejfddZedee	e
f dee	e
f fddZedd	 Zejd
d	 Zeedejfde	dee	 defddZ		ddee	ejf dee defddZdS )PreprocessorzBase of preprocessors.
    c                 O   sH   || _ | j tjtjtjfv sJ dtjv rttjd | _d S d | _d S )N
LOCAL_RANK)	_moder   	INFERENCETRAINEVALosenvironintdevice)selfmodeargskwargs r&   Q/home/ubuntu/.local/lib/python3.10/site-packages/modelscope/preprocessors/base.py__init__   s   

zPreprocessor.__init__datareturnc                 C   s   d S Nr&   )r"   r)   r&   r&   r'   __call__   s   zPreprocessor.__call__c                 C   s   | j S r+   r   )r"   r&   r&   r'   r#      s   zPreprocessor.modec                 C   s
   || _ d S r+   r-   )r"   valuer&   r&   r'   r#      s   
Nmodel_name_or_pathrevisioncfg_dictc                 K   s  t j|st||tjtjig dd}n|}|du r t|}n|}|j}d|v r.|	d}t
|}	d|v r<|	d}	|tjkrCdnd}
t|drQt|jd	krZtd
 t }n|j}d|vrw|
|v rkt||
}ntd|
 d |}n|}|d|i || d|v rt|trtdt||	}n[td| d| d t|dt }t|dr|jnt|dd}|du s|du rtd| d| d dS ||ftvrtd||f d dS tdt||f i|}t||	}||_|	dd t|ds||_|S )ag	  Instantiate a preprocessor 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 used to load the preprocessor out.
            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 config. If provided, it will replace
                the config read out of the `model_name_or_path`
            preprocessor_mode(str, `optional`): Specify the working mode of the preprocessor, can be `train`, `eval`,
                or `inference`. Default value `inference`.
                The preprocessor field in the config may contain two sub preprocessors:
                >>> {
                >>>     "train": {
                >>>         "type": "some-train-preprocessor"
                >>>     },
                >>>     "val": {
                >>>         "type": "some-eval-preprocessor"
                >>>     }
                >>> }
                In this scenario, the `train` preprocessor will be loaded in the `train` mode, the `val` preprocessor
                will be loaded in the `eval` or `inference` mode. The `mode` field in the preprocessor class
                will be assigned in all the modes.
                Or just one:
                >>> {
                >>>     "type": "some-train-preprocessor"
                >>> }
                In this scenario, the sole preprocessor will be loaded in all the modes,
                and the `mode` field in the preprocessor class will be assigned.

            **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 preprocessor does not have a `type` field and the task to be used is not
                equal to the task of which the model is saved.
                Other kwargs will be directly fed into the preprocessor, to replace the default configs.

        Returns:
            The preprocessor instance.

        Examples:
            >>> from modelscope.preprocessors import Preprocessor
            >>> Preprocessor.from_pretrained('damo/nlp_debertav2_fill-mask_chinese-base')

        )z.*.binz.*.tsz.*.ptz.*.data-00000-of-00001z.*.onnxz.*.metaz.*.pbz.*.index)r0   
user_agentignore_file_patternNtaskfieldtrainvalpreprocessorr   z#No preprocessor field found in cfg.typezNo zJ key and type key found in preprocessor domain of configuration.json file.	model_dirzNot supported yet!z;Cannot find available config to build preprocessor at mode z, current config: z0. trying to build by task and model information.model
model_typezFind task: z, model type: zL. Insufficient information to build preprocessor, skip building preprocessorzNo preprocessor key z7 found in PREPROCESSOR_MAP, skip building preprocessor.cfg)r   pathexistsr   r   KEYPREPROCESSORr   r4   popr   find_field_by_taskr   r   hasattrlenr8   loggerwarningr   getattrupdate
isinstancer   NotImplementedErrorr   r9   PREPROCESSOR_MAPr#   r=   )clsr/   r0   r1   preprocessor_moder%   r:   r=   r4   
field_namesub_keypreprocessor_cfgsub_cfgr8   	model_cfgr<   r&   r&   r'   from_pretrained   s   4











zPreprocessor.from_pretrainedtarget_folderconfigsave_config_functionc                 C   s   |du rt | dr| j}|durPd|v r=|d dur=d|d v r'd|d d< nd|d v r=d|d d v r=d|d d d< |du rIddlm} |}||| dS dS )	as  Save the preprocessor, its configuration and other related files to a directory,
            so that it can be re-loaded

        By default, this method will save the preprocessor's config with mode `inference`.

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

            config (Optional[dict], optional):
                The config for the configuration.json

            save_config_function (Callable): The function used to save the configuration, call this function
                after the config is updated.
        Nr=   r8   r#   	inferencer7   r   )save_configuration)rD   r=   modelscope.utils.checkpointrY   )r"   rU   rV   rW   rY   r&   r&   r'   save_pretrainedY  s"   zPreprocessor.save_pretrained)NN)__name__
__module____qualname____doc__r   r   r(   r   r   strr   r,   propertyr#   setterclassmethodr   r   r   rT   r	   r   PathLikedictr   r[   r&   r&   r&   r'   r      s<    $

 r   )]r   abcr   r   typingr   r   r   r   r   r	   modelscope.metainfor
   r   r   modelscope.utils.configr   r   modelscope.utils.constantr   r   r   r   modelscope.utils.hubr   r   modelscope.utils.loggerr   builderr   rF   canmtcompetency_aware_translationcanmt_translationbarttext_error_correctionbertbackbonesen_cls_tokenizerdocument_segmentation	fill_masksentence_embeddingtext_classification&speaker_diarization_dialogue_detectionnlisentiment_classificationsentence_similarityzero_shot_classificationtext_rankingpart_of_speechtoken_cls_tokenizertoken_classification3speaker_diarization_semantic_speaker_turn_detectionword_segmentationbloomtext_gen_tokenizergpt_neosentence_piecepalmT5text2text_gen_preprocessortext2text_generation
deberta_v2ponetfill_mask_ponet
structbertfaq_question_answering#faq_question_answering_preprocessortoken_classification_for_nernamed_entity_recognitiondoc2bot!document_grounded_dialog_generatedocument_grounded_dialog_rerank"document_grounded_dialog_retrievalvecolcrfsequence_labeling_tokenizer	lcrf_wseg	tcrf_wsegtcrffeature_extractioninformation_extractionre_tokenizertext_generationtinynas_detectionimage_object_detection%object_detection_tinynas_preprocessortinynas_damoyolo domain_specific_object_detectioncontrollable_image_generation*controllable_image_generation_preprocessorrL   r   r&   r&   r&   r'   <module>   s   


	











!
#
%
)
.
4
8
:
>
@
D
H
J
L
N
P
R
T
V
X
Z
\
^
b
d
f
j
l
n
p
r
t
x
z
|
~ 
  













  &