o
    1jO                     @   s@   d dl mZ d dlZddlmZ ddlmZ G dd deZdS )	    )UnionN   )abspath   )
BaseConfigc                   @   s  e Zd ZdZdefddZdefddZdefdd	Z	
dd
ddededefddZ	dde
defddZdefddZde
fddZdefddZde
fd d!Zd"e
fd#d$Zd%e
fd&d'Zd(efd)d*Zd+ed
ef fd,d-Zd.e
fd/d0Zd1efd2d3Zd4efd5d6Zd7efd8d9Zd:e
fd;d<Zd=efd>d?Zd@efdAdBZdCefdDdEZdFefdGdHZdIe
fdJdKZ dLed
ef fdMdNZ!dOefdPdQZ"dRe
fdSdTZ#dUe
fdVdWZ$dXe
fdYdZZ%d[d\ Z&d]efd^d_Z'dd`edaefdbdcZ(ddefdedfZ)dgefdhdiZ*d`efdjdkZ+d=efdldmZ,dnefdodpZ-dqefdrdsZ.dOefdtduZ/dvdw Z0dxdy Z1dzd{ Z2d|e
fd}d~Z3d|e
fddZ4d|e
fddZ5d|e
fddZ6d|efddZ7d|e
fddZ8d|efddZ9dd|e
fddZ:d|e
fddZ;d|efddZ<d|efddZ=d|efddZ>d|efddZ?d
S )	ClsConfigz Image Classification Task Configlist_like_objc                 C   s&   ddl m} || j|}| | dS )zupdate self

        Args:
            list_like_obj (list): list of pairs(key0.key1.idx.key2=value), such as:
                [
                    'topk=2',
                    'VALID.transforms.1.ResizeImage.resize_short=300'
                ]
        r   )override_configN)Zpaddleclas.ppcls.utils.configr	   dictreset_from_dict)selfr   r	   dict_ r   l/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/paddlex/repo_apis/PaddleClas_api/cls/config.pyupdate   s   
zClsConfig.updateconfig_file_pathc                 C   s2   t jt|dt jd}t|tst| | dS )zload config from yaml file

        Args:
            config_file_path (str): the path of yaml file.

        Raises:
            TypeError: the content of yaml file `config_file_path` error.
        rbLoaderN)yamlloadopenr   
isinstancer
   	TypeErrorr   )r   r   r   r   r   r   r   )   s   	
zClsConfig.loadc                 C   sH   t |ddd}tj| j|ddd W d   dS 1 sw   Y  dS )zvdump self to yaml file

        Args:
            config_file_path (str): the path to save self as yaml file.
        wzutf-8)encodingF)Zdefault_flow_style	sort_keysN)r   r   dumpr
   )r   r   fr   r   r   r   7   s   "zClsConfig.dumpN)train_list_pathdataset_pathdataset_typer   c             	   C   s   t |}|du r
d}|r| }n| d}|dv r:d| d| d| d| d	| d
| dd| dg}n	tt| d| | dS )a_  update dataset settings

        Args:
            dataset_path (str): the root path of dataset.
            dataset_type (str, optional): dataset type. Defaults to None.
            train_list_path (str, optional): the path of train dataset annotation file . Defaults to None.

        Raises:
            ValueError: the dataset_type error.
        N
ClsDatasetz
/train.txt)r"   ZMLClsDatasetzDataLoader.Train.dataset.name=z$DataLoader.Train.dataset.image_root=z(DataLoader.Train.dataset.cls_label_path=zDataLoader.Eval.dataset.name=z#DataLoader.Eval.dataset.image_root=z'DataLoader.Eval.dataset.cls_label_path=z/val.txtz$Infer.PostProcess.class_id_map_file=z
/label.txtz is not supported.)r   
ValueErrorreprr   )r   r    r!   r   Zds_cfgr   r   r   update_dataset@   s"   



zClsConfig.update_datasettrain
batch_sizemodec                 C   s   |dkr | j d d ddrd| g}n$d| g}dg}n|d	kr+d
| g}n|dkr6d| g}ntd| | dS )a7  update batch size setting

        Args:
            batch_size (int): the batch size number to set.
            mode (str, optional): the mode that to be set batch size, must be one of 'train', 'eval', 'test'.
                Defaults to 'train'.

        Raises:
            ValueError: `mode` error.
        r&   Trainsamplerr'   Fz$DataLoader.Train.sampler.batch_size=z"DataLoader.Train.sampler.first_bs=z/DataLoader.Train.dataset.name=MultiScaleDatasetevalz#DataLoader.Eval.sampler.batch_size=testzDataLoader.Infer.batch_size=z/The input `mode` should be train, eval or test.N)
DataLoadergetr#   r   )r   r'   r(   _cfgr   r   r   update_batch_sizeg   s   zClsConfig.update_batch_sizelearning_ratec                 C   sf   | j d d dddurd| g}n| j d d dddur(d| g}ntd| | dS )	zoupdate learning rate

        Args:
            learning_rate (float): the learning rate value to set.
        	Optimizerlrr1   NzOptimizer.lr.learning_rate=Zmax_learning_ratezOptimizer.lr.max_learning_rate=zunsupported lr format)_dictr.   r#   r   )r   r1   r/   r   r   r   update_learning_rate   s   zClsConfig.update_learning_ratewarmup_epochsc                 C      d| g}|  | dS )zmupdate warmup epochs

        Args:
            warmup_epochs (int): the warmup epochs value to set.
        zOptimizer.lr.warmup_epoch=Nr   )r   r6   r/   r   r   r   update_warmup_epochs      zClsConfig.update_warmup_epochspretrained_modelc                 C   s   t |ttdfsJ d|du r| dg | dg dS | dkr3| dg | dg dS |ds@t|dd	}| d
| g dS )zupdate pretrained weight path

        Args:
            pretrained_model (str): the local path or url of pretrained weight file to set.
        NzThe 'pretrained_model' should be a string, indicating the path to the '*.pdparams' file, or 'None', indicating that no pretrained model to be used.zGlobal.pretrained_model=NonezArch.pretrained=FalsedefaultzArch.pretrained=True)zhttp://zhttps://	.pdparams zGlobal.pretrained_model=)r   strtyper   lower
startswithr   replace)r   r;   r   r   r   update_pretrained_weights   s    

z#ClsConfig.update_pretrained_weightsnum_classesc                 C   sp   d| g}|   dkr|d|  |d|  | jdd}|dur1| | | | | | dS )zmupdate classes number

        Args:
            num_classes (int): the classes number value to set.
        zArch.class_num=ZDistillationModelz Arch.models.0.Teacher.class_num=z Arch.models.1.Student.class_num=	MLDecoderN)_get_arch_nameappendr
   r.   update_ml_query_numupdate_ml_class_numr   )r   rE   Zupdate_str_listZ
ml_decoderr   r   r   update_num_classes   s   

zClsConfig.update_num_classes	query_numc                 C   <   | j di dd}|durd| g}| | dS dS )zupdate MLDecoder query number
        Args:
            query_num (int): the query number value to set,qury_num should be less than or equal to num_classes.
        rF   rL   NzMLDecoder.query_num=r
   r.   r   )r   rL   Zbase_query_numr/   r   r   r   rI      
   zClsConfig.update_ml_query_num	class_numc                 C   rM   )ztupdate MLDecoder query number
        Args:
            num_classes (int): the classes number value to set.
        rF   rP   NzMLDecoder.class_num=rN   )r   rP   Zbase_class_numr/   r   r   r   rJ      rO   zClsConfig.update_ml_class_numslim_config_pathc                 C   s0   t jt|dt jdd }| d| g dS )zsupdate slim settings

        Args:
            slim_config_path (str): the path to slim config yaml file.
        r   r   SlimzSlim=N)r   r   r   r   r   )r   rQ   Zslim_configr   r   r   _update_slim_config   s   zClsConfig._update_slim_configampc                 C   s\   |du s|dkrd| j v r| jd dS dS d| j vr tddd| g}| | dS )zupdate AMP settings

        Args:
            amp (None | str): the AMP settings.

        Raises:
            ValueError: AMP setting `amp` error, missing field `AMP`.
        NZOFFAMPz!Config must have AMP information.zAMP.use_amp=Truez
AMP.level=)r
   r4   popr#   r   )r   rT   r/   r   r   r   _update_amp   s   	

zClsConfig._update_ampnum_workersc                 C   s"   d| d| g}|  | dS )zupdate workers number of train and eval dataloader

        Args:
            num_workers (int): the value of train and eval dataloader workers number to set.
        z$DataLoader.Train.loader.num_workers=z#DataLoader.Eval.loader.num_workers=Nr8   )r   rX   r/   r   r   r   update_num_workers   s   zClsConfig.update_num_workersshared_memeoryc                 C   4   t |ts	J dd| d| g}| | dS )zupdate shared memory setting of train and eval dataloader

        Args:
            shared_memeory (bool): whether or not to use shared memory
        zshared_memeory should be a boolz*DataLoader.Train.loader.use_shared_memory=z)DataLoader.Eval.loader.use_shared_memory=Nr   boolr   )r   rZ   r/   r   r   r   update_shared_memory   
   zClsConfig.update_shared_memoryshufflec                 C   r[   )zupdate shuffle setting of train and eval dataloader

        Args:
            shuffle (bool): whether or not to shuffle the data
        zshuffle should be a boolz DataLoader.Train.loader.shuffle=zDataLoader.Eval.loader.shuffle=Nr\   )r   r`   r/   r   r   r   update_shuffle
  r_   zClsConfig.update_shuffledalic                 C   s4   t |ts	J dd| d| g}| | dS )z|enable DALI setting of train and eval dataloader

        Args:
            dali (bool): whether or not to use DALI
        zdali should be a boolzGlobal.use_dali=Nr\   )r   rb   r/   r   r   r   update_dali  r_   zClsConfig.update_daliseedc                 C   r7   )zXupdate seed

        Args:
            seed (int): the random seed value to set
        zGlobal.seed=Nr8   )r   rd   r/   r   r   r   update_seed$  r:   zClsConfig.update_seeddevicec                 C   s(   | dd }d| g}| | dS )zaupdate device setting

        Args:
            device (str): the running device to set
        :r   zGlobal.device=Nsplitr   )r   rf   r/   r   r   r   update_device-  s   zClsConfig.update_device	dict_pathc                 C   s   dt | g}| | dS )zsupdate label dict file path

        Args:
            dict_path (str): the path of label dict file to set
        z#PostProcess.Topk.class_id_map_file=N)r   r   )r   rk   r/   r   r   r   update_label_dict_path7  s   z ClsConfig.update_label_dict_pathdy2stc                 C      |  d| g dS )zupdate config to set dynamic to static mode

        Args:
            dy2st (bool): whether or not to use the dynamic to static mode.
        zGlobal.to_static=Nr8   )r   rm   r   r   r   _update_to_staticB     zClsConfig._update_to_staticuse_vdlc                 C   rn   )zqupdate config to set VisualDL

        Args:
            use_vdl (bool): whether or not to use VisualDL.
        zGlobal.use_visualdl=Nr8   )r   rq   r   r   r   _update_use_vdlJ  rp   zClsConfig._update_use_vdlepochsc                 C   rn   )zfupdate epochs setting

        Args:
            epochs (int): the epochs number value to set
        zGlobal.epochs=Nr8   )r   rs   r   r   r   _update_epochsR  rp   zClsConfig._update_epochsresume_pathc                 C   s*   |dur
| dd}| d| g dS )zupdate checkpoint setting

        Args:
            resume_path (None | str): the resume training setting. if is `None`, train from scratch, otherwise,
                train from checkpoint file that path is `.pdparams` file.
        Nr=   r>   zGlobal.checkpoints=)rC   r   )r   ru   r   r   r   _update_checkpointsZ  s   zClsConfig._update_checkpointssave_dirc                 C      |  dt| g dS )zeupdate output directory

        Args:
            save_dir (str): the path to save outputs.
        zGlobal.output_dir=Nr   r   r   rw   r   r   r   _update_output_dire     zClsConfig._update_output_dirlog_intervalc                 C   rn   )zqupdate log interval(steps)

        Args:
            log_interval (int): the log interval value to set.
        zGlobal.print_batch_step=Nr8   )r   r}   r   r   r   update_log_intervalm  rp   zClsConfig.update_log_intervaleval_intervalc                 C   rn   )zuupdate eval interval(epochs)

        Args:
            eval_interval (int): the eval interval value to set.
        zGlobal.eval_interval=Nr8   )r   r   r   r   r   update_eval_intervalu  rp   zClsConfig.update_eval_intervalsave_intervalc                 C   rn   )zuupdate eval interval(epochs)

        Args:
            save_interval (int): the save interval value to set.
        zGlobal.save_interval=Nr8   )r   r   r   r   r   update_save_interval}  rp   zClsConfig.update_save_intervalc                 C   s&   | dd }| d| dg dS )z\update log ranks

        Args:
            device (str): the running device to set
        rg      zGlobal.log_ranks=""Nrh   )r   rf   Z	log_ranksr   r   r   update_log_ranks  s   zClsConfig.update_log_ranksprint_mem_infoc                 C   s(   t |ts	J d| d| g dS )zsetting print memory infozprint_mem_info should be a boolzGlobal.print_mem_info=Nr\   )r   r   r   r   r   update_print_mem_info  s   zClsConfig.update_print_mem_info	infer_img
infer_listc                 C   s,   |r|  d| g |  d| g dS )zupdate image to be predicted

        Args:
            infer_img (str): the path to image that to be predicted.
            infer_list (str, optional): the path to file that images. Defaults to None.
        zInfer.infer_list=zInfer.infer_imgs=Nr8   )r   r   r   r   r   r   _update_predict_img  s   zClsConfig._update_predict_imgsave_inference_dirc                 C   rx   )zupdate directory path to save inference model files

        Args:
            save_inference_dir (str): the directory path to set.
        zGlobal.save_inference_dir=Nry   )r   r   r   r   r   _update_save_inference_dir  r|   z$ClsConfig._update_save_inference_dir	model_dirc                 C   rx   )zupdate inference model directory

        Args:
            model_dir (str): the directory path of inference model fils that used to predict.
        zGlobal.inference_model_dir=Nry   )r   r   r   r   r   _update_inference_model_dir  r|   z%ClsConfig._update_inference_model_dirc                 C   rn   )zoupdate path of image that would be predict

        Args:
            infer_img (str): the image path.
        zGlobal.infer_imgs=Nr8   )r   r   r   r   r   _update_infer_img  rp   zClsConfig._update_infer_imgc                 C   s$   |  d|dd dk g dS )zqupdate the device used in predicting

        Args:
            device (str): the running device setting
        zGlobal.use_gpu=rg   r   ZgpuN)r   ri   )r   rf   r   r   r   _update_infer_device  s   $zClsConfig._update_infer_deviceenable_mkldnnc                 C   rn   )zupdate whether to enable MKLDNN

        Args:
            enable_mkldnn (bool): `True` is enable, otherwise is disable.
        zGlobal.enable_mkldnn=Nr8   )r   r   r   r   r   _update_enable_mkldnn  rp   zClsConfig._update_enable_mkldnn	img_shapec                 C   rn   )zupdate image cropping shape in the preprocessing

        Args:
            img_shape (str): the shape of cropping in the preprocessing,
                i.e. `PreProcess.transform_ops.1.CropImage.size`.
        z*PreProcess.transform_ops.1.CropImage.size=Nr8   )r   r   r   r   r   _update_infer_img_shape  s   z!ClsConfig._update_infer_img_shapec                 C   rn   )zupdate directory that save predicting output

        Args:
            save_dir (str): the directory path that save predicting output.
        zInfer.save_dir=Nr8   rz   r   r   r   _update_save_predict_result  rp   z%ClsConfig._update_save_predict_resultc                 K   .   |D ]}|| }|  d| d| g qdS )zupdate model settingszArch.=Nr8   r   kwargskvr   r   r   update_model     zClsConfig.update_modelc                 K   r   )zupdate teacher model settingszArch.models.0.Teacher.r   Nr8   r   r   r   r   update_teacher_model  r   zClsConfig.update_teacher_modelc                 K   r   )zupdate student model settingszArch.models.1.Student.r   Nr8   r   r   r   r   update_student_model  r   zClsConfig.update_student_modelreturnc                 C      | j d d S )ziget epochs

        Returns:
            int: the epochs value, i.e., `Global.epochs` in config.
        Globalrs   r
   r   r   r   r   get_epochs_iters     zClsConfig.get_epochs_itersc                 C   r   )zget log interval(steps)

        Returns:
            int: the log interval value, i.e., `Global.print_batch_step` in config.
        r   Zprint_batch_stepr   r   r   r   r   get_log_interval  r   zClsConfig.get_log_intervalc                 C   r   )zget eval interval(epochs)

        Returns:
            int: the eval interval value, i.e., `Global.eval_interval` in config.
        r   r   r   r   r   r   r   get_eval_interval  r   zClsConfig.get_eval_intervalc                 C   r   )zget save interval(epochs)

        Returns:
            int: the save interval value, i.e., `Global.save_interval` in config.
        r   r   r   r   r   r   r   get_save_interval  r   zClsConfig.get_save_intervalc                 C      | j d d d S )zget learning rate

        Returns:
            float: the learning rate value, i.e., `Optimizer.lr.learning_rate` in config.
        r2   r3   r1   r   r   r   r   r   get_learning_rate	     zClsConfig.get_learning_ratec                 C   r   )zget warmup epochs

        Returns:
            int: the warmup epochs value, i.e., `Optimizer.lr.warmup_epochs` in config.
        r2   r3   Zwarmup_epochr   r   r   r   r   get_warmup_epochs  r   zClsConfig.get_warmup_epochsc                 C   r   )zget label dict file path

        Returns:
            str: the label dict file path, i.e., `PostProcess.Topk.class_id_map_file` in config.
        ZPostProcessZTopkZclass_id_map_filer   r   r   r   r   get_label_dict_path  r   zClsConfig.get_label_dict_pathc                 C      | j d d d d S )a:  get batch size

        Args:
            mode (str, optional): the mode that to be get batch size value, must be one of 'train', 'eval', 'test'.
                Defaults to 'train'.

        Returns:
            int: the batch size value of `mode`, i.e., `DataLoader.{mode}.sampler.batch_size` in config.
        r-   r)   r*   r'   r   )r   r(   r   r   r   get_batch_size!  s   
zClsConfig.get_batch_sizec                 C      |   S )zLget qat epochs

        Returns:
            int: the epochs value.
        )r   r   r   r   r   get_qat_epochs_iters-     zClsConfig.get_qat_epochs_itersc                 C   r   )z\get qat learning rate

        Returns:
            float: the learning rate value.
        )r   r   r   r   r   get_qat_learning_rate5  r   zClsConfig.get_qat_learning_ratec                 C   r   )z|get architecture name of model

        Returns:
            str: the model arch name, i.e., `Arch.name` in config.
        ZArchnamer   r   r   r   r   rG   =  r   zClsConfig._get_arch_namec                 C   r   )zget root directory of dataset, i.e. `DataLoader.Train.dataset.image_root`

        Returns:
            str: the root directory of dataset
        r-   r)   ZdatasetZ
image_rootr   r   r   r   r   _get_dataset_rootE  rp   zClsConfig._get_dataset_rootc                 C   s   | d d S )ziget the directory to save output

        Returns:
            str: the directory to save output
        r   
output_dirr   r   r   r   r   get_train_save_dirM  s   zClsConfig.get_train_save_dir)N)r&   )@__name__
__module____qualname____doc__listr   r?   r   r   r%   intr0   floatr5   r9   rD   rK   rI   rJ   rS   r   rW   rY   r]   r^   ra   rc   re   rj   rl   ro   rr   rt   rv   r{   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rG   r   r   r   r   r   r   r      s    
'	

	
		r   )typingr   r   Z
utils.miscr   baser   r   r   r   r   r   <module>   s
   