o
    1jQS                     @   s  d dl Z d dlZd dlZd dlZd dlZd dlZddl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 dd	lmZ dd
lmZmZmZ ddgZdddZeZG dd de jdZG dd deZG dd de Z!G dd de!Z"G dd de!Z#G dd de!Z$dS )    N   )flagslogging)get_cache_dir)parse_device)UnsupportedAPIErrorUnsupportedParamError)CachedProperty   )Config)build_model_from_model_infobuild_runner_from_model_infoget_registered_model_infoPaddleModel	BaseModelc              
   C   s   | du r|du rt d| dur|dur| |jkrt dn| du r)|dur)|j} zt| }W n tyE } z
tt|  d|d}~ww t||dS )_create_modelNz;At least one of `model_name` and `config` must be not None.zgIf both `model_name` and `config` are not None, `model_name` should be the same as `config.model_name`.z  is not a registered model name.)
model_infoconfig)
ValueError
model_namer   KeyErrorr   reprr   )r   r   r   e r   ]/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/paddlex/repo_apis/base/model.pyr   &   s*   
r   c                       s8  e Zd ZdZdZdZd- fdd	Zej											
	d.ddZ	ej						d/ddZ
ejd0ddZejdd Zejd0ddZej					
	d1ddZejdd Zejdd Zedd Zedd Zedd  Zed!d" Zed#d$ Zed%d& Zed'd( Zed)d* Zd+d, Z  ZS )2r   z
    Abstract base class of Model.

    Model defines how Config and Runner interact with each other. In addition,
    Model provides users with multiple APIs to perform model training,
    prediction, etc.
    )trainevaluatepredictexportinfercompressionzsupported_{api_name}_optsNc                    sR   t    || _t|| _t| j| _|du r td t	|}|| _
|   dS )z
        Initialize the instance.

        Args:
            model_name (str): A registered model name.
            config (base.config.BaseConfig|None): Config. Default: None.
        Na  We strongly discourage leaving `config` unset or setting it to None. Please note that when `config` is None, default settings will be used for every unspecified configuration item, which may lead to unexpected result. Please make sure that this is what you intend to do.)super__init__namer   r   r   runnerr   warningr   r   _patch_apis)selfr   r   	__class__r   r   r"   J   s   

zBaseModel.__init__gpuFOFFTc                 K      t )a  
        Train a model.

        Args:
            batch_size (int|None): Number of samples in each mini-batch. If
                multiple devices are used, this is the batch size on each device.
                If None, use a default setting. Default: None.
            learning_rate (float|None): Learning rate of model training. If
                None, use a default setting. Default: None.
            epochs_iters (int|None): Total epochs or iterations of model
                training. If None, use a default setting. Default: None.
            ips (str|None): If not None, enable multi-machine training mode.
                `ips` specifies Paddle cluster node ips, e.g.,
                '192.168.0.16,192.168.0.17'. Default: None.
            device (str): A string that describes the device(s) to use, e.g.,
                'cpu', 'gpu', 'gpu:1,2'. Default: 'gpu'.
            resume_path (str|None): If not None, resume training from the model
                snapshot corresponding to the weight file `resume_path`. If
                None, use a default setting. Default: None.
            dy2st (bool): Whether to enable dynamic-to-static training.
                Default: False.
            amp (str): Optimization level to use in AMP training. Choices are
                ['O1', 'O2', 'OFF']. Default: 'OFF'.
            num_workers (int|None): Number of subprocesses to use for data
                loading. If None, use a default setting. Default: None.
            use_vdl (bool): Whether to enable VisualDL during training.
                Default: True.
            save_dir (str|None): Directory to store model snapshots and logs. If
                None, use a default setting. Default: None.

        Returns:
            paddlex.repo_apis.base.utils.subprocess.CompletedProcess
        NotImplementedError)r'   
batch_sizelearning_rateepochs_itersipsdeviceZresume_pathdy2stampnum_workersuse_vdlsave_dirkwargsr   r   r   r   e   s   1zBaseModel.trainc                 K   r,   )a  
        Evaluate a model.

        Args:
            weight_path (str): Path of the weights to initialize the model.
            batch_size (int|None): Number of samples in each mini-batch. If
                multiple devices are used, this is the batch size on each device.
                If None, use a default setting. Default: None.
            ips (str|None): If not None, enable multi-machine evaluation mode.
                `ips` specifies Paddle cluster node ips, e.g.,
                '192.168.0.16,192.168.0.17'. Default: None.
            device (str): A string that describes the device(s) to use, e.g.,
                'cpu', 'gpu', 'gpu:1,2'. Default: 'gpu'.
            amp (str): Optimization level to use in AMP training. Choices are
                ['O1', 'O2', 'OFF']. Default: 'OFF'.
            num_workers (int|None): Number of subprocesses to use for data
                loading. If None, use a default setting. Default: None.

        Returns:
            paddlex.repo_apis.base.utils.subprocess.CompletedProcess
        r-   )r'   weight_pathr/   r2   r3   r5   r6   r9   r   r   r   r      s    zBaseModel.evaluatec                 K   r,   )a2  
        Make prediction with a pre-trained model.

        Args:
            weight_path (str): Path of the weights to initialize the model.
            input_path (str): Path of the input file, e.g. an image.
            device (str): A string that describes the device to use, e.g.,
                'cpu', 'gpu'. Default: 'gpu'.
            save_dir (str|None): Directory to store prediction results. If None,
                use a default setting. Default: None.

        Returns:
            paddlex.repo_apis.base.utils.subprocess.CompletedProcess
        r-   )r'   r:   
input_pathr3   r8   r9   r   r   r   r         zBaseModel.predictc                 K   r,   )a"  
        Export a pre-trained model.

        Args:
            weight_path (str): Path of the weights to initialize the model.
            save_dir (str): Directory to store the exported model.

        Returns:
            paddlex.repo_apis.base.utils.subprocess.CompletedProcess
        r-   )r'   r:   r8   r9   r   r   r   r      s   zBaseModel.exportc                 K   r,   )a2  
        Make inference with an exported inference model.

        Args:
            model_dir (str): Path of the exported inference model.
            input_path (str): Path of the input file, e.g. an image.
            device (str): A string that describes the device(s) to use, e.g.,
                'cpu', 'gpu'. Default: 'gpu'.
            save_dir (str|None): Directory to store inference results. If None,
                use a default setting. Default: None.

        Returns:
            paddlex.repo_apis.base.utils.subprocess.CompletedProcess
        r-   )r'   Z	model_dirr;   r3   r8   r9   r   r   r   r      r<   zBaseModel.inferc           	      K   r,   )ak  
        Perform quantization aware training (QAT) and export the quantized
        model.

        Args:
            weight_path (str): Path of the weights to initialize the model.
            batch_size (int|None): Number of samples in each mini-batch. If
                multiple devices are used, this is the batch size on each
                device. If None, use a default setting. Default: None.
            learning_rate (float|None): Learning rate of QAT. If None, use a
                default setting. Default: None.
            epochs_iters (int|None): Total epochs of iterations of model
                training. If None, use a default setting. Default: None.
            device (str): A string that describes the device(s) to use, e.g.,
                'cpu', 'gpu'. Default: 'gpu'.
            use_vdl (bool): Whether to enable VisualDL during training.
                Default: True.
            save_dir (str|None): Directory to store the results. If None, use a
                default setting. Default: None.

        Returns:
            tuple[paddlex.repo_apis.base.utils.subprocess.CompletedProcess]
        r-   )	r'   r:   r/   r0   r1   r3   r7   r8   r9   r   r   r   r       s   #zBaseModel.compressionc              	   c       | j }| jd }d|j |g}|d }tjsUtjt	 d*}t
j||}t|ddd W d    n1 s;w   Y  |V  W d    d S 1 sNw   Y  d S t
jt	 |}t|ddd W d    n1 sow   Y  |V  d S )Nr   _z.ymldirwutf-8encodingr)   r   join__name__lowerr   DEBUGtempfileTemporaryDirectoryr   ospathopen)r'   clsr   tagZyaml_file_nametdrM   r   r   r   _create_new_config_file  $   
"
z!BaseModel._create_new_config_filec              	   c   r=   )Nr   r>   z
_test.jsonr?   rA   rB   rC   rE   )r'   rO   r   rP   Zjson_file_namerQ   rM   r   r   r   _create_new_val_json_file#  rS   z#BaseModel._create_new_val_json_filec                 C      | j ddS )zsupported apissupported_apisNr   getr'   r   r   r   rV   5     zBaseModel.supported_apisc                 C      | j | jjdddS )zsupported train optsr   api_nameNr   rX   _API_SUPPORTED_OPTS_KEY_PATTERNformatrY   r   r   r   supported_train_opts:     zBaseModel.supported_train_optsc                 C   r[   )zsupported evaluate optsr   r\   Nr^   rY   r   r   r   supported_evaluate_optsA  rb   z!BaseModel.supported_evaluate_optsc                 C   r[   )zsupported predcit optsr   r\   Nr^   rY   r   r   r   supported_predict_optsH  rb   z BaseModel.supported_predict_optsc                 C   r[   )zsupported infer optsr   r\   Nr^   rY   r   r   r   supported_infer_optsO  rb   zBaseModel.supported_infer_optsc                 C   r[   )zsupported copression optsr    r\   Nr^   rY   r   r   r   supported_compression_optsV  rb   z$BaseModel.supported_compression_optsc                 C   rU   )zsupported dataset typessupported_dataset_typesNrW   rY   r   r   r   rg   ]  rZ   z!BaseModel.supported_dataset_typesc                 C   s&   t | dkrtd|  d d S d S )Nr   z'Unconsumed keyword arguments detected: .)lenr   r%   )r9   r   r   r   _assert_empty_kwargsb  s   zBaseModel._assert_empty_kwargsc                    s    fdd} fdd} j }|d urt j }nt j} jD ]#}t |}||vr7||}t || q!tjrD||}t || q!d S )Nc                    s   t   fdd}|S )Nc                     s    j } j}t| d| d)Nz does not support `z`.)r#   rG   r   )argsr9   r   r]   )
bnd_methodr'   r   r   _unavailable_apim  s
   zJBaseModel._patch_apis.<locals>._make_unavailable.<locals>._unavailable_api)	functoolswraps)rl   rm   rY   )rl   r   _make_unavailablel  s   z0BaseModel._patch_apis.<locals>._make_unavailablec                    s  t   fdd} j}g |dkrGj}|d urEd|v r+t|d dd d|v r8t|d  d|v rEt|d  |S |d	krpj}|d urnd|v rat|d dd d|v rnt|d  |S |d
krj	}|d urd|v rt|d dd |S |dkrj
}|d urd|v rt|d dd |S |dkrĈj}|d urd|v rt|d dd |S  S )Nc                     sv   t j }|j| i |}|j}|j D ]}|j|vr)|j|j	ur)|j||j< qD ]}|
| q, | i |S N)inspect	Signaturefrom_callablebind	arguments
parametersvaluesr#   defaultemptycheck)rk   r9   sigZbnd_argsZ	args_dictpr{   rl   Zchecksr   r   _api_with_prechecksx  s   zJBaseModel._patch_apis.<locals>._add_prechecks.<locals>._api_with_prechecksr   r3   T)check_mcr4   r5   r   r   Fr   r    )rn   ro   rG   ra   append_CheckDevice_CheckDy2St	_CheckAMPrc   rd   re   rf   )rl   r   r]   optsrY   r~   r   _add_prechecksw  sR   	z-BaseModel._patch_apis.<locals>._add_prechecks)rV   set_API_FULL_LISTgetattrsetattrr   Z
CHECK_OPTS)r'   rp   r   rV   Zavail_api_setr]   apiZdecorated_apir   rY   r   r&   k  s    9


zBaseModel._patch_apisrq   )NNNNr*   NFr+   NTN)NNr*   r+   N)r*   N)NNNr*   TN)rG   
__module____qualname____doc__r   r_   r"   abcabstractmethodr   r   r   r   r   r    
contextlibcontextmanagerrR   rT   cached_propertyrV   ra   rc   rd   re   rf   rg   staticmethodrj   r&   __classcell__r   r   r(   r   r   >   sx    2!
$









)	metaclassc                   @   s$   e Zd Zd ZdZdd Zdd ZdS )_CheckFailedTc                 C   s   || _ || _|| _d S rq   )arg_namearg_val
legal_vals)r'   r   r   r   r   r   r   r"     s   
z_CheckFailed.__init__c                 C   s   d| j  d| j d| j S )N`z*` is expected to be one of or conforms to z
, but got )r   r   r   rY   r   r   r   __str__  s   z_CheckFailed.__str__N)rG   r   r   r   Zcheck_failed_errorr"   r   r   r   r   r   r     s
    r   c                       s(   e Zd Zd Z fddZdd Z  ZS )_APICallArgsCheckerc                    s   t    || _d S rq   )r!   r"   r   )r'   r   r(   r   r   r"     s   

z_APICallArgsChecker.__init__c                 C   r,   )r{   r-   )r'   rk   r   r   r   r{     s   z_APICallArgsChecker.checkrG   r   r   r   r"   r{   r   r   r   r(   r   r     s    r   c                       s*   e Zd Zd Zd fdd	Zdd Z  ZS )r   Fc                    s   t  | || _d S rq   )r!   r"   r   )r'   r   r   r(   r   r   r"     s   
z_CheckDevice.__init__c                 C   s4  d|v sJ |d }|durt |\}}| js%|| jvr#td|| jdS |dkr7|| jvr5td|| jdS | d}| d}| d}t|dkrh|| jvrb|| jvrd|| jvrftd|| jdS dS dS d|v snJ |d dur|| jvrtd|| jdS || jvr|| jvrtd|| jdS dS 	 dS )	r{   r3   Nr*   Z_n1c1Z_n1cxZ_nxcxr
   r2   )r   r   r   r   ri   )r'   rk   r3   Zdevice_typeZdev_idsZ	n1c1_descZ	n1cx_descZ	nxcx_descr   r   r   r{     sD   










z_CheckDevice.check)Fr   r   r   r(   r   r     s    r   c                   @      e Zd Zd Zdd ZdS )r   c                 C   sx   d|v sJ |d }t | jtr!t| jdksJ t| jd }nt| j}|dur9|r5|s7td||gdS dS 	 dS )r{   r4   r
   r   N)
isinstancer   listri   boolr   )r'   rk   r4   Zsupport_dy2str   r   r   r{     s   
z_CheckDy2St.checkNrG   r   r   r   r{   r   r   r   r   r         r   c                   @   r   )r   c                 C   sJ   d|v sJ |d }|dur"|dkr|| j vr td|| j dS dS 	 dS )r{   r5   Nr+   )r   r   )r'   rk   r5   r   r   r   r{   +  s   z_CheckAMP.checkNr   r   r   r   r   r   (  r   r   )NN)%r   r   rn   rr   rL   rJ   utilsr   r   Zutils.cacher   Zutils.devicer   Zutils.errorsr   r   Z
utils.miscr	   r   r   r   registerr   r   r   __all__r   r   ABCMetar   	Exceptionr   objectr   r   r   r   r   r   r   r   <module>   s2   
   4