U
    Ph`                     @  s  d dl m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 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lmZmZmZmZ d dlmZ d dl m!Z!m"Z"m#Z#m$Z$m%Z% ddgZ&ee'dZ(G dd deZ)G dd de)Z*dS )    )annotationsN)ABCabstractmethod)copy)
fileConfig)Path)AnySequence)
get_logger)ConfigParser)InferPropertiesMetaPropertiesTrainProperties)DEFAULT_EXP_MGMT_SETTINGSEXPR_KEY
ID_REF_KEY
ID_SEP_KEY)PathLike)BundlePropertyBundlePropertyConfigdeprecated_argdeprecated_arg_defaultensure_tupleBundleWorkflowConfigWorkflow)module_namec                      s  e Zd ZU dZdZded< dZded< eddd	d
ddd4ddddddddZe	ddddddZ
e	ddddddZe	ddddddZe	dddddd Ze	ddddd!d"d#Zd$d% Z fd&d'Zd(d) Zd*d+ Zd5dddd,d-d.d/Zd0d1d2d3Z  ZS )6r   a  
    Base class for the workflow specification in bundle, it can be a training, evaluation or inference workflow.
    It defines the basic interfaces for the bundle workflow behavior: `initialize`, `run`, `finalize`, etc.
    And also provides the interface to get / set public properties to interact with a bundle workflow.

    Args:
        workflow_type: specifies the workflow type: "train" or "training" for a training workflow,
            or "infer", "inference", "eval", "evaluation" for a inference workflow,
            other unsupported string will raise a ValueError.
            default to `None` for common workflow.
        workflow: specifies the workflow type: "train" or "training" for a training workflow,
            or "infer", "inference", "eval", "evaluation" for a inference workflow,
            other unsupported string will raise a ValueError.
            default to `None` for common workflow.
        properties_path: the path to the JSON file of properties.
        meta_file: filepath of the metadata file, if this is a list of file paths, their contents will be merged in order.
        logging_file: config file for `logging` module in the program. for more details:
            https://docs.python.org/3/library/logging.config.html#logging.config.fileConfig.

    )traintrainingtuplesupported_train_type)infer	inferenceevalZ
evaluationsupported_infer_typeworkflow1.21.5workflow_type#please use `workflow_type` instead.sinceremovednew_name
msg_suffixN
str | NonePathLike | Nonestr | Sequence[str] | None)r'   r$   properties_path	meta_filelogging_filec              	   C  s  |d k	rBt j|s$td| dtd| d t|dd |d k	rt|trvt j|svt	d| d d }t|t
r|D ]&}t j|st	d| d d }q|d k	r|n|}|d kr|d krtt| _d | _|| _d S |d k	rBt|}| std| d	t|}t|| _W 5 Q R X d | _|| _d S | | jkrdtt| _d
| _n2| | jkrtt| _d| _ntd| d|| _d S )N%Cannot find the logging config file: .,Setting logging properties based on config: FZdisable_existing_loggersz&Cannot find the metadata config file: zC. Please see: https://docs.monai.io/en/stable/mb_specification.htmlzProperty file z does not exist.r   r    zUnsupported workflow type: 'z'.)ospathisfileFileNotFoundErrorloggerinfor   
isinstancestrerrorlistr   r   
propertiesr'   r2   r   is_file
ValueErroropenjsonloadlowerr   r   r#   r   )selfr'   r$   r1   r2   r3   f	json_file rL   K/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/bundle/workflows.py__init__=   sR    








zBundleWorkflow.__init__r   )argskwargsreturnc                 O  s
   t  dS )A
        Initialize the bundle workflow before running.

        NNotImplementedErrorrI   rO   rP   rL   rL   rM   
initialize|   s    zBundleWorkflow.initializec                 O  s
   t  dS )zZ
        Run the bundle workflow, it can be a training, evaluation or inference.

        NrS   rU   rL   rL   rM   run   s    zBundleWorkflow.runc                 O  s
   t  dS )F
        Finalize step after the running of bundle workflow.

        NrS   rU   rL   rL   rM   finalize   s    zBundleWorkflow.finalizer?   dictnamepropertyrQ   c                 C  s
   t  dS )a  
        With specified property name and information, get the expected property value.

        Args:
            name: the name of target property.
            property: other information for the target property, defined in `TrainProperties` or `InferProperties`.

        NrS   )rI   r\   r]   rL   rL   rM   _get_property   s    
zBundleWorkflow._get_propertyr\   r]   valuerQ   c                 C  s
   t  dS )I  
        With specified property name and information, set value for the expected property.

        Args:
            name: the name of target property.
            property: other information for the target property, defined in `TrainProperties` or `InferProperties`.
            value: value to set for the property.

        NrS   )rI   r\   r]   r`   rL   rL   rM   _set_property   s    zBundleWorkflow._set_propertyc                 C  s6   | j d k	r(|| j kr(| j|| j | dS | |S d S )Nr\   r]   )rB   r^   __getattribute__)rI   r\   rL   rL   rM   __getattr__   s    zBundleWorkflow.__getattr__c                   sF   |dkr4| j d k	r4|| j kr4| j|| j | |d nt || d S )NrB   )r\   r]   r`   )rB   rb   super__setattr__)rI   r\   r`   	__class__rL   rM   rg      s    zBundleWorkflow.__setattr__c                 C  s   | j S )zP
        Get the workflow type, it can be `None`, "train", or "infer".

        )r'   rI   rL   rL   rM   get_workflow_type   s    z BundleWorkflow.get_workflow_typec                 C  s   | j S )z%
        Get the meta file.

        )r2   rj   rL   rL   rM   get_meta_file   s    zBundleWorkflow.get_meta_fileNone)r\   requireddescrQ   c                 C  sF   | j dkri | _ || j kr,td| d tj|tj|i| j |< dS )a  
        Besides the default predefined properties, some 3rd party applications may need the bundle
        definition to provide additional properties for the specific use cases, if the bundle can't
        provide the property, means it can't work with the application.
        This utility adds the property for the application requirements check and access.

        Args:
            name: the name of target property.
            required: whether the property is "must-have".
            desc: descriptions for the property.
        Nz
property 'z7' already exists in the properties list, overriding it.)rB   r<   warnr   DESCREQUIRED)rI   r\   rn   ro   rL   rL   rM   add_property   s
    

zBundleWorkflow.add_propertylist[str] | NonerQ   c                   s&    j dkrdS  fdd j  D S )z
        Check whether the required properties are existing in the bundle workflow.
        If no workflow type specified, return None, otherwise, return a list of required but missing properties.

        Nc                   s,   g | ]$\}}| tjd rt |s|qS )F)getr   rr   hasattr).0nprj   rL   rM   
<listcomp>   s      
 z3BundleWorkflow.check_properties.<locals>.<listcomp>)rB   itemsrj   rL   rj   rM   check_properties   s    
zBundleWorkflow.check_properties)NNNNN)N)__name__
__module____qualname____doc__r   __annotations__r#   r   rN   r   rV   rW   rY   r^   rb   re   rg   rk   rl   rs   r}   __classcell__rL   rL   rh   rM   r   $   s@   
	     8c                      s,  e Zd ZdZeddddddeddd	dd
dd;ddddddddddddd fddZddddZddddZddd d!Z	d"d fd#d$Z
dd%dd&d'd(Zdd%dd)d*d+Zdd%dd)d,d-Zdd%ddd.d/d0Zd<dddddd1 fd2d3Zdd%d4d)d5d6Zed7d%dd8d9d:Z  ZS )=r   a  
    Specification for the config-based bundle workflow.
    Standardized the `initialize`, `run`, `finalize` behavior in a config-based training, evaluation, or inference.
    Before `run`, we add bundle root directory to Python search directories automatically.
    For more information: https://docs.monai.io/en/latest/mb_specification.html.

    Args:
        config_file: filepath of the config file, if this is a list of file paths, their contents will be merged in order.
        meta_file: filepath of the metadata file, if this is a list of file paths, their contents will be merged in order.
            If None, default to "configs/metadata.json", which is commonly used for bundles in MONAI model zoo.
        logging_file: config file for `logging` module in the program. for more details:
            https://docs.python.org/3/library/logging.config.html#logging.config.fileConfig.
            If None, default to "configs/logging.conf", which is commonly used for bundles in MONAI model zoo.
            If False, the logging logic for the bundle will not be modified.
        init_id: ID name of the expected config expression to initialize before running, default to "initialize".
            allow a config to have no `initialize` logic and the ID.
        run_id: ID name of the expected config expression to run, default to "run".
            to run the config, the target config must contain this ID.
        final_id: ID name of the expected config expression to finalize after running, default to "finalize".
            allow a config to have no `finalize` logic and the ID.
        tracking: if not None, enable the experiment tracking at runtime with optionally configurable and extensible.
            if "mlflow", will add `MLFlowHandler` to the parsed bundle with default tracking settings,
            if other string, treat it as file path to load the tracking settings.
            if `dict`, treat it as tracking settings.
            will patch the target config content with `tracking handlers` and the top-level items of `configs`.
            for detailed usage examples, please check the tutorial:
            https://github.com/Project-MONAI/tutorials/blob/main/experiment_management/bundle_integrate_mlflow.ipynb.
        workflow_type: specifies the workflow type: "train" or "training" for a training workflow,
            or "infer", "inference", "eval", "evaluation" for a inference workflow,
            other unsupported string will raise a ValueError.
            default to `None` for common workflow.
        workflow: specifies the workflow type: "train" or "training" for a training workflow,
            or "infer", "inference", "eval", "evaluation" for a inference workflow,
            other unsupported string will raise a ValueError.
            default to `None` for common workflow.
        properties_path: the path to the JSON file of properties.
        override: id-value pairs to override or add the corresponding config content.
            e.g. ``--net#input_chns 42``, ``--net %/data/other.json#net_arg``

    r$   r%   r&   r'   r(   r)   Nr   z1.4)r*   replacedrV   rW   rY   zstr | Sequence[str]r0   zstr | bool | Noner?   zstr | dict | Noner.   r/   r   rm   )config_filer2   r3   init_idrun_idfinal_idtrackingr'   r$   r1   overriderQ   c                   s  |	d k	r|	n|}|d k	r|t |}t|d j}|D ]F}t|}|j|kr`td| d| d | s2td| dq2ntd}|d krt|d n|}t j	|||
d	 || _
|d krt| j
d
 n|}|dkrtd| d njtj|s2|t| j
d
 kr td| d ntd| dn"td| d tt|dd t | _| jj|d | jd k	r| jj| jd | jj|d || _|| _|| _|d k	rt|tr|tkrt| }n
t|}| j| j|d d| _d S )Nr   zNot all config files are in z2. If logging_file and meta_file arenot specified, z3 will be used as the default config root directory.zCannot find the config file: r5   configszmetadata.json)r'   r2   r1   zlogging.confFzLogging file is set to z, skipping logging.zDefault logging file in z" does not exist, skipping logging.r4   r6   r7   )rJ   )pairs)parsersettings)r   r   parentr<   rp   rC   r;   r?   rf   rN   config_root_pathr8   r9   r:   r=   r   r   r   read_configr2   	read_metaupdater   r   r   r>   r   load_config_filespatch_bundle_tracking_is_initialized)rI   r   r2   r3   r   r   r   r   r'   r$   r1   r   Z_config_filesr   Z_config_fileZ	settings_rh   rL   rM   rN     sN    



zConfigWorkflow.__init__ru   c                 C  s"   | j jdd d| _| j| jdS )rR   T)resetid)r   parser   	_run_exprr   rj   rL   rL   rM   rV   V  s    zConfigWorkflow.initializec                 C  sX   | j jdkr| j jn| j }tjdt| | j| jkrJt	d| j d| j
| jdS )z
        Run the bundle workflow, it can be a training, evaluation or inference.
        Before run, we add bundle root directory to Python search directories automatically.

        r      zrun ID 'z#' doesn't exist in the config file.r   )r   r\   r   sysr9   insertr?   r   r   rD   r   )rI   Z_bundle_root_pathrL   rL   rM   rW   `  s    zConfigWorkflow.runc                 C  s   | j | jdS )rX   r   )r   r   rj   rL   rL   rM   rY   n  s    zConfigWorkflow.finalizert   c                   s   t   }| jdkr"td dS |r6td|  g }| j D ].\}}|tjdsD| j	||dsD|
| qD|rtd|  |dk	r|| |S )aD  
        Check whether the required properties are existing in the bundle workflow.
        If the optional properties have reference in the config, will also check whether the properties are existing.
        If no workflow type specified, return None, otherwise, return a list of required but missing properties.

        Nz5No available properties had been set, skipping check.zBLoaded bundle does not contain the following required properties: Frc   zGLoaded bundle defines the following optional properties with wrong ID: )rf   r}   rB   r<   rp   r|   rv   r   rr   _check_optional_idappendextend)rI   retZwrong_propsry   rz   rh   rL   rM   r}   u  s    



zConfigWorkflow.check_propertiesrZ   )r   rP   rQ   c                 K  s   || j kr| j j|f|S d S )N)r   get_parsed_content)rI   r   rP   rL   rL   rM   r     s    zConfigWorkflow._run_exprr[   c                 C  s@   |t j }|| jkr<|tjds&d S td| d| d|S )NFz
Property 'z' with config ID 'z' not in the config.)r   IDr   rv   r   rr   KeyErrorrI   r\   r]   prop_idrL   rL   rM   _get_prop_id  s    

zConfigWorkflow._get_prop_idc                 C  s4   | j std| ||}|dk	r0| jj|dS dS )a  
        With specified property name and information, get the parsed property value from config.

        Args:
            name: the name of target property.
            property: other information for the target property, defined in `TrainProperties` or `InferProperties`.

        z>Please execute 'initialize' before getting any parsed content.Nr   )r   RuntimeErrorr   r   r   r   rL   rL   rM   r^     s    	zConfigWorkflow._get_propertyr_   c                 C  s4   |  ||}|dk	r0|| j|< d| _| jj  dS )ra   NF)r   r   r   ref_resolverr   )rI   r\   r]   r`   r   rL   rL   rM   rb     s
    

zConfigWorkflow._set_property)r\   rn   	config_idro   rQ   c                   s&   t  j|||d || j| tj< dS )ao  
        Besides the default predefined properties, some 3rd party applications may need the bundle
        definition to provide additional properties for the specific use cases, if the bundle can't
        provide the property, means it can't work with the application.
        This utility adds the property for the application requirements check and access.

        Args:
            name: the name of target property.
            required: whether the property is "must-have".
            config_id: the config ID of target property in the bundle definition.
            desc: descriptions for the property.

        )r\   rn   ro   N)rf   rs   rB   r   r   )rI   r\   rn   r   ro   rh   rL   rM   rs     s    zConfigWorkflow.add_propertyboolc                 C  s   | tjd}| tjd}|dkr(dS d}|dkrxdt d| jkr| jdt d D ]}|d dkrX| |d}qXn| j |d}|dk	r|ts|t| krdS dS )	a  
        If an optional property has reference in the config, check whether the property is existing.
        If `ValidationHandler` is defined for a training workflow, will check whether the optional properties
        "evaluator" and "val_interval" are existing.

        Args:
            name: the name of target property.
            property: other information for the target property, defined in `TrainProperties` or `InferProperties`.

        NT)	evaluatorval_intervalr   handlers_target_ZValidationHandlerF)	rv   r   r   REF_IDr   r   
startswithr   r   )rI   r\   r]   r   ref_idrefhrL   rL   rM   r     s    z!ConfigWorkflow._check_optional_idr   )r   r   rQ   c                 C  s:  |d   D ]\}}||d kr| |d | d }|dk	r| |d | d }|dkrt|g||dkrndnd< q|| q|| kr|| |< qd	td
 d}| dd}|r.t|trd| krt t d| d< | d d| d | d< t	j
| d|}t|jjddd | |  | nd| d< dS )a,  
        Patch the loaded bundle config with a new handler logic to enable experiment tracking features.

        Args:
            parser: loaded config content to patch the handler.
            settings: settings for the experiment tracking, should follow the pattern of default settings.

        r   handlers_idr   Nr   trainertrain_handlersval_handlersZconfig_z%Y%m%d_%H%M%Sz.jsonsave_execute_configT
output_dirzbundle_root + '/eval'z + '/')parentsexist_ok)r|   rv   r   timestrftimer>   r   r   r   r8   r9   joinr   r   r   mkdirexport_config_file)r   r   kvenginer   default_namefilepathrL   rL   rM   r     s*    

z$ConfigWorkflow.patch_bundle_tracking)	NNrV   rW   rY   NNNN)N)r~   r   r   r   r   r   rN   rV   rW   rY   r}   r   r   r^   rb   rs   r   staticmethodr   r   rL   rL   rh   rM   r      s@   )         .@
	 )+
__future__r   rF   r8   r   r   abcr   r   r   Zlogging.configr   pathlibr   typingr   r	   monai.apps.utilsr
   monai.bundle.config_parserr   Zmonai.bundle.propertiesr   r   r   monai.bundle.utilsr   r   r   r   monai.configr   monai.utilsr   r   r   r   r   __all__r~   r<   r   r   rL   rL   rL   rM   <module>   s(   
 A