
    |-jQS                     b   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ZeZ G d de j                  Z G d de          Z G d de           Z! G d de!          Z" G d de!          Z# G 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                 $   | |t          d          | || |j        k    rt          d          n| 	||j        } 	 t          |           }n2# t          $ r%}t	          t          |            d          |d}~ww xY wt          ||          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   es       \/var/www/html/banglarbhumi/venv/lib/python3.11/site-packages/paddlex/repo_apis/base/model.pyr   r   &   s    fnVWWW		F$6***   +
 
	 2&
.z::

   #JAAA
 
	 '*VLLLLs   A 
A> A99A>c                       e Zd ZdZdZdZd fd	Zej        	 	 	 	 	 	 	 	 	 	 	 dd
            Z	ej        	 	 	 	 	 dd            Z
ej        dd            Zej        d             Zej        dd            Zej        	 	 	 	 	 	 dd            Zej        d             Zej        d             Zed             Zed             Zed             Zed             Zed             Zed             Zed             Zed             Zd Z xZS ) r   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                 0   t                                                       || _        t          |          | _        t          | j                  | _        |#t          j        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__s      r   r%   zBaseModel.__init__J   s     		3J?? 34?CC>Ol   J''F    gpuFOFFTc                     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deviceresume_pathdy2stampnum_workersuse_vdlsave_dirkwargss                r   r   zBaseModel.traine   s    b "!r,   c                     t           )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
        r0   )r*   weight_pathr2   r5   r6   r9   r:   r=   s           r   r   zBaseModel.evaluate   s    @ "!r,   c                     t           )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
        r0   )r*   r?   
input_pathr6   r<   r=   s         r   r   zBaseModel.predict   
      "!r,   c                     t           )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
        r0   )r*   r?   r<   r=   s       r   r    zBaseModel.export   s
     "!r,   c                     t           )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
        r0   )r*   	model_dirrA   r6   r<   r=   s         r   r!   zBaseModel.infer   rB   r,   c                     t           )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]
        r0   )	r*   r?   r2   r3   r4   r6   r;   r<   r=   s	            r   r"   zBaseModel.compression   s    F "!r,   c              #   |  K   | j         }| j        d         }d                    |j                                        |g          }|dz   }t
          j        st          j        t                                5 }t          j                            ||          }t          |dd          5  	 d d d            n# 1 swxY w Y   |V  d d d            d S # 1 swxY w Y   d S t          j                            t                      |          }t          |dd          5  	 d d d            n# 1 swxY w 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   tagyaml_file_nametdrW   s          r   _create_new_config_filez!BaseModel._create_new_config_file  s     n_\2
hh**,,j9::v{ 
	,AAA Rw||B77$g666                


	                  7<<@@DdC'222                JJJJJH   73C*B8,C8B<	<C?B<	 CCCD--D14D1c              #   |  K   | j         }| j        d         }d                    |j                                        |g          }|dz   }t
          j        st          j        t                                5 }t          j                            ||          }t          |dd          5  	 d d d            n# 1 swxY w Y   |V  d d d            d S # 1 swxY w Y   d S t          j                            t                      |          }t          |dd          5  	 d d d            n# 1 swxY w Y   |V  d S )Nr   rH   z
_test.jsonrI   rK   rL   rM   rO   )r*   rY   r   rZ   json_file_namer\   rW   s          r   _create_new_val_json_filez#BaseModel._create_new_val_json_file#  s     n_\2
hh**,,j9::|+{ 
	,AAA Rw||B77$g666                


	                  7<<@@DdC'222                JJJJJr^   c                 8    | j                             dd          S )zsupported apissupported_apisNr   getr*   s    r   rc   zBaseModel.supported_apis5  s     ""#3T:::r,   c                 j    | j                             | j                            d          d          S )zsupported train optsr   api_nameNr   re   _API_SUPPORTED_OPTS_KEY_PATTERNformatrf   s    r   supported_train_optszBaseModel.supported_train_opts:  7     ""0777II4
 
 	
r,   c                 j    | j                             | j                            d          d          S )zsupported evaluate optsr   rh   Nrj   rf   s    r   supported_evaluate_optsz!BaseModel.supported_evaluate_optsA  s7     ""0777LLd
 
 	
r,   c                 j    | j                             | j                            d          d          S )zsupported predcit optsr   rh   Nrj   rf   s    r   supported_predict_optsz BaseModel.supported_predict_optsH  s7     ""0777KKT
 
 	
r,   c                 j    | j                             | j                            d          d          S )zsupported infer optsr!   rh   Nrj   rf   s    r   supported_infer_optszBaseModel.supported_infer_optsO  rn   r,   c                 j    | j                             | j                            d          d          S )zsupported copression optsr"   rh   Nrj   rf   s    r   supported_compression_optsz$BaseModel.supported_compression_optsV  s8     ""0777OOQU
 
 	
r,   c                 8    | j                             dd          S )zsupported dataset typessupported_dataset_typesNrd   rf   s    r   rx   z!BaseModel.supported_dataset_types]  s     ""#<dCCCr,   c                 `    t          |           dk    rt          j        d|  d           d S d S )Nr   z'Unconsumed keyword arguments detected: .)lenr   r(   )r=   s    r   _assert_empty_kwargszBaseModel._assert_empty_kwargsb  s:    v;;??OOfOOOPPPPP ?r,   c                 F     fd} fd} j         }|t           j                   }nt           j                  } j        D ][}t           |          }||vr ||          }t	           ||           3t
          j        r ||          }t	           ||           \d S )Nc                 J     t          j                    fd            }|S )Nc                  J    j         }j        }t          | d| d          )Nz does not support `z`.)r&   rQ   r   )argsr=   r   ri   
bnd_methodr*   s       r   _unavailable_apizJBaseModel._patch_apis.<locals>._make_unavailable.<locals>._unavailable_apim  s8    !Y
%.)!BBhBBB  r,   )	functoolswraps)r   r   r*   s   ` r   _make_unavailablez0BaseModel._patch_apis.<locals>._make_unavailablel  s?    _Z((     )( $#r,   c                     t          j                    fd            } j        }g |dk    rj        }|d|v r*                    t          |d         d                     d|v r(                    t          |d                              d|v r(                    t          |d                              n&|dk    rdj        }|Zd|v r*                    t          |d         d                     d|v r(                    t          |d                              n|d	k    r8j	        }|.d|v r*                    t          |d         d
                     n~|dk    r8j
        }|.d|v r*                    t          |d         d
                     n@|dk    r8j        }|.d|v r*                    t          |d         d                     n S |S )Nc                  2   t           j                                      } |j        | i |}|j        }|j                                        D ](}|j        |vr|j        |j	        ur|j        ||j        <   )D ]}|
                    |            | i |S N)inspect	Signaturefrom_callablebind	arguments
parametersvaluesr&   defaultemptycheck)	r   r=   sigbnd_args	args_dictpr   r   checkss	          r   _api_with_precheckszJBaseModel._patch_apis.<locals>._add_prechecks.<locals>._api_with_prechecksx  s    '55jAA#38T4V44$.	..00 6 6AvY..19AG3K3K,-I	!&) $ + +EKK	****!z426222r,   r   r6   T)check_mcr8   r9   r   r   Fr!   r"   )r   r   rQ   rm   append_CheckDevice_CheckDy2St	_CheckAMPrp   rr   rt   rv   )r   r   ri   optsr   r*   s   `   @r   _add_prechecksz-BaseModel._patch_apis.<locals>._add_prechecksw  s0   _Z((3 3 3 3 3 )(3  "*HF7""0#4''l4>D&Q&Q&QRRR$k$w-&@&@AAA}}iU&<&<===Z''3#4''l4>D&Q&Q&QRRR}}iU&<&<===Y&&2#4''l4>E&R&R&RSSSW$$0#4''l4>E&R&R&RSSS]**6#4''l4>D&Q&Q&QRRR!!&&r,   )rc   set_API_FULL_LISTgetattrsetattrr   
CHECK_OPTS)r*   r   r   rc   avail_api_setri   apidecorated_apis   `       r   r)   zBaseModel._patch_apisk  s    		$ 		$ 		$ 		$ 		$7	' 7	' 7	' 7	' 7	'r ,% 344MM 344M+ 	; 	;H$))C},, !2 1# 6 6h6666# ; %3N3$7$7MD(M:::	; 	;r,   r   )NNNNr-   NFr.   NTN)NNr-   r.   N)r-   N)NNNr-   TN)rQ   
__module____qualname____doc__r   rk   r%   abcabstractmethodr   r   r   r    r!   r"   
contextlibcontextmanagerr]   ra   cached_propertyrc   rm   rp   rr   rt   rv   rx   staticmethodr|   r)   __classcell__r+   s   @r   r   r   >   s         XN&A#     6 	 0" 0" 0" 0"d 	 " " " "B 	" " " "" 	" " " 	" " " "" 	 "" "" "" ""H   "   " ; ; _; 
 
 _
 
 
 _
 
 
 _
 
 
 _
 
 
 _
 D D _D Q Q \QX; X; X; X; X; X; X;r,   )	metaclassc                   "    e Zd Zd ZdZd Zd ZdS )_CheckFailedTc                 0    || _         || _        || _        d S r   )arg_namearg_val
legal_vals)r*   r   r   r   s       r   r%   z_CheckFailed.__init__  s     $r,   c                 6    d| j          d| j         d| j         S )N`z*` is expected to be one of or conforms to z
, but got )r   r   r   rf   s    r   __str__z_CheckFailed.__str__  s(    u4=uuDOuugkgsuuur,   N)rQ   r   r   r   check_failed_errorr%   r    r,   r   r   r     sE         % % %
v v v v vr,   r   c                   (     e Zd Zd Z fdZd Z xZS )_APICallArgsCheckerc                 V    t                                                       || _        d S r   )r$   r%   r   )r*   r   r+   s     r   r%   z_APICallArgsChecker.__init__  s$    $r,   c                     t           )r   r0   )r*   r   s     r   r   z_APICallArgsChecker.check  s    !!r,   rQ   r   r   r   r%   r   r   r   s   @r   r   r     sM        % % % % %" " " " " " "r,   r   c                   *     e Zd Zd Zd fd	Zd Z xZS )r   Fc                 X    t                                          |           || _        d S r   )r$   r%   r   )r*   r   r   r+   s      r   r%   z_CheckDevice.__init__  s&    $$$ r,   c                 R   d|v sJ |d         }|t          |          \  }}| j        s!|| j        vrt          d|| j                  dS |dk    r!|| j        vrt          d|| j                  dS | d}| d}| d}t	          |          dk    r7|| j        vr(|| j        vr!|| j        vrt          d|| j                  dS dS dS d|v sJ |d         !|| j        vrt          d|| j                  dS || j        vr|| j        vrt          d|| j                  dS dS dS )	r   r6   Nr-   _n1c1_n1cx_nxcxr   r5   )r   r   r   r   r{   )r*   r   r6   device_typedev_ids	n1c1_desc	n1cx_desc	nxcx_descs           r   r   z_CheckDevice.check  s   4h#/#7#7 K=  Vdo55&xIII 65 %''"$/99*8VT_MMM :9 $/ 5 5 5I#. 5 5 5I#. 5 5 5I7||q((%T_<< ) @ @ ) @ @".x"Q"QQ	 =< @ @ @ @  %}}}};2(??&28VT_&U&U U  @?
 !* @ @$-T_$D$D&28VT_&U&U U !A @$D$D Dr,   )Fr   r   s   @r   r   r     sR        ! ! ! ! ! !* * * * * * *r,   r   c                       e Zd Zd Zd ZdS )r   c                     d|v sJ |d         }t          | j        t                    r5t          | j                  dk    sJ t	          | j        d                   }nt	          | j                  }||r|st          d||g          dS dS dS )r   r8   r   r   N)
isinstancer   listr{   boolr   )r*   r   r8   support_dy2sts       r   r   z_CheckDy2St.check  s    $Wdot,, 	2t''1,,,, !344MM 11M D] D"7EM?CCCD D D D Dr,   NrQ   r   r   r   r   r   r,   r   r   r     s)            r,   r   c                       e Zd Zd Zd ZdS )r   c                 x    d|v sJ |d         }|)|dk    r|| j         vrt          d|| j                   dS dS dS )r   r9   Nr.   )r   r   )r*   r   r9   s      r   r   z_CheckAMP.check+  sZ    }}}}5k?e||4? : :"5#t??? | : : Dr,   Nr   r   r,   r   r   r   (  s(        O    r,   r   )NN)%r   r   r   r   rV   rT   utilsr   r   utils.cacher   utils.devicer   utils.errorsr   r	   
utils.miscr
   r   r   r   registerr   r   r   __all__r   r   ABCMetar   	Exceptionr   objectr   r   r   r   r   r,   r   <module>r      s;    


          				  # # # # # # # # ( ( ( ( ( ( ( ( ( ( ( ( F F F F F F F F ; ; ; ; ; ;                +
&M M M M* E; E; E; E; E;#+ E; E; E; E;Pv v v v v9 v v v	" 	" 	" 	" 	"& 	" 	" 	"1 1 1 1 1& 1 1 1h    %   &    #     r,   