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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 d dlmZmZ d dlZd d	lmZ d d
lmZ d dlmZmZ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'm(Z( d dl)m*Z*m+Z+ d dl,m-Z-m.Z. d dl/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5 d dl6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z= e<ddd\Z>Z?e<ddd\Z@Z?e<de*jAe;d\ZBZCe<ddd\ZDZEe<d\ZFZ?e<d\ZGZ?eeHdZIejJKd d!ZLd"ZMdd$d%d&d'd(d)d*ZNeNZOd'd&d&d+d,d-d.ZPd/d'd0d1d2d3ZQd/d4d5d6d7ZRdd9d:d:d:d+d;d<d=ZSd/d/d/d/d/d>d?d@ZTd/d/d/dAdBdCZUd/d/d/dAdDdEZVdd/dFd/d%d0dGdHdIZWdFd/d/d%d0dJdKdLZXdd/d/d/dNdOdPZYdd/d/d/dNdQdRZZdFd/d/dSd%d0dTdUdVZ[dWdX Z\d/d/d/dYdZd[d\Z]dd]dFd^d_d`Z^dddeLdddMd#df	dSdSd]d/dSdSdSd%dSd0da
dbdcZ_e8dddedfdgdhe8didedfdgdhe8djdedfdkdddlddmdeLddMd#dddndddd#ddfd/dodSd/dSd%d]d/dSdSd%dSdSdpdqdSdrd%drdSd&dsdtdudvZ`dd/d/dSdydzd{d|Zadd/d/dSd}dzd~dZbdd/d/d/dSddddZcdd/dSd/d/dSddddZdddSdSdSdddSd$dSd&d0d
ddZeddqdSd&d0dddZfddd]ddSdSdSd&d0dddZgddd/d+dddZhdd+dddZiddSdddSddddrdSd&d0dddZjddd/d/d/d/d/d&d0d	ddZkddSd]dSdddSdddSdd&d0dddZlddSd]dSdddSdddSdd&d0dddZmddSd]dSdddSdSddddddddSdd&d0dddZnddd]dod%ddd0dddZodd Zpdd/d/d/dSddSdd&d&d	ddZqddqddSd&d&dddZrddSdSd0dddZsdS )    )annotationsN)MappingSequence)Path)locate)copyfile)dedent)AnyCallable)is_available)_get_all_ngc_models)	_basenamedownload_url
extractall
get_logger)ConfigComponent)ConfigParser)DEFAULT_INFERENCEDEFAULT_METADATA)BundleWorkflowConfigWorkflow)
IgniteInfoPathLike)load_net_with_metadatasave_net_with_metadata)convert_to_onnxconvert_to_torchscriptconvert_to_trtcopy_model_stateget_state_dict
save_state)check_parent_dirdeprecated_argensure_tupleget_equivalent_dtypemin_versionoptional_importpprint_edgesZ
jsonschemavalidatenamezjsonschema.exceptionsValidationErrorzignite.handlers
Checkpointrequestsgetonnxhuggingface_hub)module_nameZBUNDLE_DOWNLOAD_SRCmonaihosting   Tzstr | dict | Noneboolr	   dict)argsignore_nonekwargsreturnc                 K  s   t | tr| ni }t | tr&t| }t | ttfrftdd | D rf| \}}t||ft||f|}t |tst|S |	 D ]P\}}|r|dkrq|t |trt |
|trt|| |f|||< q||||< q||S )a%  
    Update the `args` dictionary with the input `kwargs`.
    For dict data, recursively update the content based on the keys.

    Example::

        from monai.bundle import update_kwargs
        update_kwargs({'exist': 1}, exist=2, new_arg=3)
        # return {'exist': 2, 'new_arg': 3}

    Args:
        args: source `args` dictionary (or a json/yaml filename to read as dictionary) to update.
        ignore_none: whether to ignore input args with None value, default to `True`.
        kwargs: key=value pairs to be merged into `args`.

    c                 s  s   | ]}t |tV  qd S N)
isinstancestr).0x r?   I/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/bundle/scripts.py	<genexpr>[   s     z update_kwargs.<locals>.<genexpr>N)r;   r5   r<   r   load_config_filetuplelistallupdate_kwargsitemsr.   )r6   r7   r8   args_primary	overrideskvr?   r?   r@   rF   F   s    

 

rF   rC   )srcr6   r8   r9   c                   s,   t  fdd|D  fdd| D  S )z{
    Pop args from the `src` dictionary based on specified keys in `args` and (key, default value) pairs in `kwargs`.

    c                   s   g | ]}  |qS r?   pop)r=   irM   r?   r@   
<listcomp>s   s     z_pop_args.<locals>.<listcomp>c                   s   g | ]\}}  ||qS r?   rN   r=   rK   rL   rQ   r?   r@   rR   s   s     )rC   rG   )rM   r6   r8   r?   rQ   r@   	_pop_argsn   s    rT   r<   None)tagr6   r9   c              	   C  sN   t d|  d | D ]$\}}t d| dt|t  qt d d S )Nz*--- input summary of monai.bundle.scripts.z ---z> z: z---

)loggerinforG   r'   PPRINT_CONFIG_N)rV   r6   r*   valr?   r?   r@   _log_input_summaryv   s    r[   z	list[str])exprr9   c                 C  s   t | }dd t |D S )z
    Parse the expression and discover what variables are present in it based on ast module.

    Args:
        expr: source expression to parse.

    c                 S  s   g | ]}t |tjr|jqS r?   )r;   astNameid)r=   mr?   r?   r@   rR      s      z"_get_var_names.<locals>.<listcomp>)r]   parsewalk)r\   treer?   r?   r@   _get_var_names}   s    
rd      zSequence[str | int]int)shapepnanyr9   c                 C  s   g }| D ]}t |tr"|| qt |tr~|dkr@|| qt|D ]}|dkrHtd| dqH|t|||d qtdt| d| dqt|S )a2  
    Get spatial shape for fake data according to the specified shape pattern.
    It supports `int` number and `string` with formats like: "32", "32 * n", "32 ** p", "32 ** p *n".

    Args:
        shape: specified pattern for the spatial shape.
        p: power factor to generate fake data shape if dim of expected shape is "x**p", default to 1.
        p: multiply factor to generate fake data shape if dim of expected shape is "x*n", default to 1.
        any: specified size to generate fake data shape if dim of expected shape is "*", default to 1.

    *)rh   ri   z4only support variables 'p' and 'n' so far, but got: .z4spatial shape items must be int or string, but got:  )	r;   rf   appendr<   rd   
ValueErrorevaltyperC   )rg   rh   ri   rj   retrP   cr?   r?   r@   _get_fake_spatial_shape   s    

rt   )
repo_owner	repo_nametag_namefilenamer9   c                 C  s   d|  d| d| d| S )Nzhttps://github.com//z/releases/download/r?   )ru   rv   rw   rx   r?   r?   r@   _get_git_release_url   s    rz   )
model_nameversionr9   c                 C  s   d|    d| dS )Nz9https://api.ngc.nvidia.com/v2/models/nvidia/monaitoolkit/
/versions/z/ziplowerr{   r|   r?   r?   r@   _get_ngc_bundle_url   s    r   c              
   C  s*   d}| d|    d| d|  d| d
S )N8https://api.ngc.nvidia.com/v2/models/nvidia/monaihostingry   r}   z/files/_v.zipr~   )r{   r|   Zmonaihosting_root_pathr?   r?   r@   _get_monaihosting_bundle_url   s    r   r   )repodownload_pathrx   progressr9   c           	      C  s\   |  d\}}}d|kr |d7 }t||||d}||  }t||d |d t||dd d S )Nry   r   )rw   rx   urlfilepathhash_valr   Tr   
output_dirhas_base)splitrz   r   r   )	r   r   rx   r   ru   rv   rw   r   r   r?   r?   r@   _download_from_github   s    
r   )r   rx   r|   r   r9   c                 C  sB   t ||d}| | d| d }t||d |d t|| dd d S )Nr   r   r   r   Tr   )r   r   r   )r   rx   r|   r   r   r   r?   r?   r@   _download_from_monaihosting   s    r   monai_)r*   prefixr9   c                 C  s   |  |r| S | |  S r:   )
startswithr*   r   r?   r?   r@   _add_ngc_prefix   s    
r   c                 C  s   |  |r| t|d  S | S r:   )r   lenr   r?   r?   r@   _remove_ngc_prefix   s    
r   z
str | None)r   rx   r|   remove_prefixr   r9   c                 C  sd   t |}t||d}| | d| d }|r8t||d}| |  }t||d |d t||dd d S )Nr   r   r   r   r   Tr   )r   r   r   r   r   )r   rx   r|   r   r   r   r   extract_pathr?   r?   r@   _download_from_ngc   s    
r   c                 C  s\   d}| d|    }tddd\}}|r<||}|  ntdt|j}|d d S )	Nr   ry   r-   r.   r)   z6NGC API requires requests package.  Please install it.modellatestVersionIdStr)r   r&   raise_for_statusro   jsonloadstext)r*   r   full_urlrequests_gethas_requestsresp
model_infor?   r?   r@   '_get_latest_bundle_version_monaihosting   s    
r   z'dict[str, list[str] | str] | Any | None)sourcer*   r   r9   c                 C  s   | dkrBt |}t|}| D ]}|d |kr |d   S q d S | dkrRt|S | dkr|d\}}}t|| d| |dd S | d	krtj|d
}t|j	dkrdd |j	D }	d|	krdn|	d gd }
ndd |j
D d }
|
S td|  dd S )Nngcr*   latestr2   githubry   )r   rV   latest_versionr0   )repo_idr   c                 S  s   g | ]
}|j qS r?   r)   )r=   tr?   r?   r@   rR      s     z._get_latest_bundle_version.<locals>.<listcomp>c                 S  s   g | ]
}|j qS r?   r)   )r=   br?   r?   r@   rR      s     zZTo get the latest bundle version, source should be 'github', 'monaihosting' or 'ngc', got rl   )r   r   valuesr   r   get_bundle_versionsr0   list_repo_refsr   tagsZbranchesro   )r   r*   r   
model_dictrL   ru   rv   rw   refsall_versionsr   r?   r?   r@   _get_latest_bundle_version   s,    
r   zPathLike | None)
bundle_dirr9   c                 C  s<   | d kr4t ddd\}}|r,t| d } ntdt| S )Nz	torch.hubget_dirr)   bundlezVbundle_dir=None, but no suitable default directory computed. Upgrade Pytorch to 1.6+ ?)r&   r   ro   )r   r   has_homer?   r?   r@   _process_bundle_dir  s    r   )
r*   r|   r   r   r   r   r   r   	args_filer9   c	                 C  s  t || |||||||d	}	td|	d t|	ddddddddd	\}
}}}}}}}t|}|dkrdd}t|d	d
kr|
dkrtdn"t|d	dkr|
dkrtd|dk	r|dk	r|| d }n|t|  }t||d|d t	||dd n|dkrtd|
 d|dkr*t
|
||d}|
dkr^|dk	rLd||g}t||||d nt|
dkrzt||||d nX|
dkrt|||||d n:|
dkrtj||}tj|||d ntd|
 ddS ) a  
    download bundle from the specified source or url. The bundle should be a zip file and it
    will be extracted after downloading.
    This function refers to:
    https://pytorch.org/docs/stable/_modules/torch/hub.html

    Typical usage examples:

    .. code-block:: bash

        # Execute this module as a CLI entry, and download bundle from the model-zoo repo:
        python -m monai.bundle download --name <bundle_name> --version "0.1.0" --bundle_dir "./"

        # Execute this module as a CLI entry, and download bundle from specified github repo:
        python -m monai.bundle download --name <bundle_name> --source "github" --repo "repo_owner/repo_name/release_tag"

        # Execute this module as a CLI entry, and download bundle from ngc with latest version:
        python -m monai.bundle download --name <bundle_name> --source "ngc" --bundle_dir "./"

        # Execute this module as a CLI entry, and download bundle from monaihosting with latest version:
        python -m monai.bundle download --name <bundle_name> --source "monaihosting" --bundle_dir "./"

        # Execute this module as a CLI entry, and download bundle from Hugging Face Hub:
        python -m monai.bundle download --name "bundle_name" --source "huggingface_hub" --repo "repo_owner/repo_name"

        # Execute this module as a CLI entry, and download bundle via URL:
        python -m monai.bundle download --name <bundle_name> --url <url>

        # Set default args of `run` in a JSON / YAML file, help to record and simplify the command line.
        # Other args still can override the default args at runtime.
        # The content of the JSON / YAML file is a dictionary. For example:
        # {"name": "spleen", "bundle_dir": "download", "source": ""}
        # then do the following command for downloading:
        python -m monai.bundle download --args_file "args.json" --source "github"

    Args:
        name: bundle name. If `None` and `url` is `None`, it must be provided in `args_file`.
            for example:
            "spleen_ct_segmentation", "prostate_mri_anatomy" in model-zoo:
            https://github.com/Project-MONAI/model-zoo/releases/tag/hosting_storage_v1.
            "monai_brats_mri_segmentation" in ngc:
            https://catalog.ngc.nvidia.com/models?filters=&orderBy=scoreDESC&query=monai.
        version: version name of the target bundle to download, like: "0.1.0". If `None`, will download
            the latest version (or the last commit to the `main` branch in the case of Hugging Face Hub).
        bundle_dir: target directory to store the downloaded data.
            Default is `bundle` subfolder under `torch.hub.get_dir()`.
        source: storage location name. This argument is used when `url` is `None`.
            In default, the value is achieved from the environment variable BUNDLE_DOWNLOAD_SRC, and
            it should be "ngc", "monaihosting", "github", or "huggingface_hub".
        repo: repo name. This argument is used when `url` is `None` and `source` is "github" or "huggingface_hub".
            If `source` is "github", it should be in the form of "repo_owner/repo_name/release_tag".
            If `source` is "huggingface_hub", it should be in the form of "repo_owner/repo_name".
        url: url to download the data. If not `None`, data will be downloaded directly
            and `source` will not be checked.
            If `name` is `None`, filename is determined by `monai.apps.utils._basename(url)`.
        remove_prefix: This argument is used when `source` is "ngc". Currently, all ngc bundles
            have the ``monai_`` prefix, which is not existing in their model zoo contrasts. In order to
            maintain the consistency between these two sources, remove prefix is necessary.
            Therefore, if specified, downloaded folder name will remove the prefix.
        progress: whether to display a progress bar.
        args_file: a JSON or YAML file to provide default values for all the args in this function.
            so that the command line inputs can be simplified.

    )	r6   r*   r|   r   r   r   r   r   r   downloadrV   r6   r   r   N)r   r   r*   r|   r   r   z*Project-MONAI/model-zoo/hosting_storage_v1ry      r0   zArepo should be in the form of `repo_owner/repo_name/release_tag`.   zEHugging Face Hub repo should be in the form of `repo_owner/repo_name`r   r   Tr   zTo download from source: z, `name` must be provided.)r   r*   r   r   r   )r   r   rx   r   r2   )r   rx   r|   r   r   )r   rx   r|   r   r   )r   revision	local_dirz|Currently only download from `url`, source 'github', 'monaihosting', 'huggingface_hub' or 'ngc' are implemented,got source: rl   )rF   r[   rT   r   r   r   ro   r   r   r   r   joinr   r   r   ospathr0   snapshot_downloadNotImplementedError)r*   r|   r   r   r   r   r   r   r   _argsZsource_Z	progress_Zremove_prefix_Zrepo_Zname_Zversion_bundle_dir_Zurl_r   r   r?   r?   r@   r     sx    K        








r   net_namez1.2z1.5zplease use ``model`` instead.)sinceremoved
msg_suffix
net_kwargsreturn_state_dict)r   r   trainFr?   ztorch.nn.Module | NonezSequence[str]zstr | BundleWorkflow | Nonezdict | Nonez1object | tuple[torch.nn.Module, dict, dict] | Any)r*   r   r|   workflow_type
model_fileload_ts_moduler   r   r   r   r   devicekey_in_ckptconfig_filesworkflow_namer   copy_model_argsr   net_overrider   r   r9   c              
   K  s>  |r|dk	s|dk	rt d t|}|dkr2i n|}|dkrBi n|}|dkr\t rXdnd}|dkr~tjd|dkrxdnd}|d	krt| } |	rt| |	d
} tj|| |}tj	|st
| |||||	|
|d |dkrt|t||dS tj|t|d}t|ts2t d| dt| d t|}|r<|S d}|dkr|dkr||  d | d }| rdd | D }tf ||t||d|}nt d| d |S |dk	r
t|dst d |S |j}n$|dk	r
||d< t|d}| }|| tf ||dkr(|n|| d| |S )a  
    Load model weights or TorchScript module of a bundle.

    Args:
        name: bundle name. If `None` and `url` is `None`, it must be provided in `args_file`.
            for example:
            "spleen_ct_segmentation", "prostate_mri_anatomy" in model-zoo:
            https://github.com/Project-MONAI/model-zoo/releases/tag/hosting_storage_v1.
            "monai_brats_mri_segmentation" in ngc:
            https://catalog.ngc.nvidia.com/models?filters=&orderBy=scoreDESC&query=monai.
            "mednist_gan" in monaihosting:
            https://api.ngc.nvidia.com/v2/models/nvidia/monaihosting/mednist_gan/versions/0.2.0/files/mednist_gan_v0.2.0.zip
        model: a pytorch module to be updated. Default to None, using the "network_def" in the bundle.
        version: version name of the target bundle to download, like: "0.1.0". If `None`, will download
            the latest version. If `source` is "huggingface_hub", this argument is a Git revision id.
        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 `train` for training workflow.
        model_file: the relative path of the model weights or TorchScript module within bundle.
            If `None`, "models/model.pt" or "models/model.ts" will be used.
        load_ts_module: a flag to specify if loading the TorchScript module.
        bundle_dir: directory the weights/TorchScript module will be loaded from.
            Default is `bundle` subfolder under `torch.hub.get_dir()`.
        source: storage location name. This argument is used when `model_file` is not existing locally and need to be
            downloaded first.
            In default, the value is achieved from the environment variable BUNDLE_DOWNLOAD_SRC, and
            it should be "ngc", "monaihosting", "github", or "huggingface_hub".
        repo: repo name. This argument is used when `url` is `None` and `source` is "github" or "huggingface_hub".
            If `source` is "github", it should be in the form of "repo_owner/repo_name/release_tag".
            If `source` is "huggingface_hub", it should be in the form of "repo_owner/repo_name".
        remove_prefix: This argument is used when `source` is "ngc". Currently, all ngc bundles
            have the ``monai_`` prefix, which is not existing in their model zoo contrasts. In order to
            maintain the consistency between these three sources, remove prefix is necessary.
            Therefore, if specified, downloaded folder name will remove the prefix.
        progress: whether to display a progress bar when downloading.
        device: target device of returned weights or module, if `None`, prefer to "cuda" if existing.
        key_in_ckpt: for nested checkpoint like `{"model": XXX, "optimizer": XXX, ...}`, specify the key of model
            weights. if not nested checkpoint, no need to set.
        config_files: extra filenames would be loaded. The argument only works when loading a TorchScript module,
            see `_extra_files` in `torch.jit.load` for more details.
        workflow_name: specified bundle workflow name, should be a string or class, default to "ConfigWorkflow".
        args_file: a JSON or YAML file to provide default values for all the args in "download" function.
        copy_model_args: other arguments for the `monai.networks.copy_model_state` function.
        return_state_dict: whether to return state dict, if True, return state_dict, else a corresponding network
            from `_workflow.network_def` will be instantiated and load the achieved weights.
        net_override: id-value pairs to override the parameters in the network of the bundle, default to `None`.
        net_name: if not `None`, a corresponding network will be instantiated and load the achieved weights.
            This argument only works when loading weights.
        net_kwargs: other arguments that are used to instantiate the network class defined by `net_name`.

    Returns:
        1. If `load_ts_module` is `False` and `model` is `None`,
            return model weights if can't find "network_def" in the bundle,
            else return an instantiated network that loaded the weights.
        2. If `load_ts_module` is `False` and `model` is not `None`,
            return an instantiated network that loaded the weights.
        3. If `load_ts_module` is `True`, return a triple that include a TorchScript module,
            the corresponding metadata dict, and extra files dict.
            please check `monai.data.load_net_with_metadata` for more details.
        4. If `return_state_dict` is True, return model weights, only used for compatibility
            when `model` and `net_name` are all `None`.

    NzUIncompatible values: model and net_name are all specified, return state dict instead.cuda:0cpumodelsTmodel.tsmodel.ptr   r   )r*   r|   r   r   r   r   r   r   )map_locationmore_extra_files)r   zthe state dictionary from z  should be a dictionary but got rl   configs.jsonc                 S  s   i | ]\}}d | |qS )znetwork_def#r?   )r=   keyvaluer?   r?   r@   
<dictcomp>  s      zload.<locals>.<dictcomp>)r   r   config_filer   zCannot find the config file: z, return state dict instead.network_defzINo available network definition in the bundle, return state dict instead._target_)configdstrM   )warningswarnr   r   r   r   r   r   r   existsr   r   torchr   loadr;   r   rq   r   is_filerG   create_workflowr<   hasattrr   r   instantiatetor   )r*   r   r|   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   	full_pathr   Z	_workflowZbundle_config_fileZ_net_overrideZconfigerr?   r?   r@   r     s    Z






 r   Project-MONAI/model-zoodevz$dict[str, dict[str, dict[str, Any]]])r   rV   
auth_tokenr9   c                 C  sp  t rb|dkrd|  d}nd|  d| d}|d k	rPdd| i}t||d	}nt|}|  ntd
t|j}td}i }|dkr|D ]x}	|	d |kr|	d D ]V}
|	|
d d }||kri ||< |
d 	| dd 
dd}t|
|| |< q|  S qn^| D ]T}
|	|
d }||kr:i ||< |
	| dd }|
||
 d d|| |< q|S )NZhosting_storage_v1zhttps://api.github.com/repos/z	/releasesz"https://raw.githubusercontent.com/ry   z/models/model_info.jsonAuthorizationzBearer )headersz0requests package is required, please install it.z_v\d*.rw   Zassetsr*   r   r   r   r    r   )r*   Zbrowser_download_url)r   r   r   ro   r   r   r   recompiler   replacer5   keys)r   rV   r   request_urlr   r   Zreleases_listZbundle_name_patternbundles_inforeleaseZassetZ
asset_nameZasset_versionr?   r?   r@   _get_all_bundles_info=  s@    


 

r  zlist[tuple[str, str]]c                 C  sB   t | ||d}g }|D ]&}t||  d }|||f q|S )a*  
    Get all bundles names (and the latest versions) that are stored in the release of specified repository
    with the provided tag. If tag is "dev", will get model information from
    https://raw.githubusercontent.com/repo_owner/repo_name/dev/models/model_info.json.
    The default values of arguments correspond to the release of MONAI model zoo. In order to increase the
    rate limits of calling Github APIs, you can input your personal access token.
    Please check the following link for more details about rate limiting:
    https://docs.github.com/en/rest/overview/resources-in-the-rest-api#rate-limiting

    The following link shows how to create your personal access token:
    https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token

    Args:
        repo: it should be in the form of "repo_owner/repo_name/".
        tag: the tag name of the release.
        auth_token: github personal access token.

    Returns:
        a list of tuple in the form of (bundle name, latest version).

    r   rV   r   r   )r  sortedr  rn   )r   rV   r   r  Zbundles_listbundle_namer   r?   r?   r@   get_all_bundles_listi  s    r  zdict[str, list[str] | str])r  r   rV   r   r9   c                 C  sN   t |||d}| |kr,td|  d| d||  }t| }|d |dS )a  
    Get the latest version, as well as all existing versions of a bundle that is stored in the release of specified
    repository with the provided tag. If tag is "dev", will get model information from
    https://raw.githubusercontent.com/repo_owner/repo_name/dev/models/model_info.json.
    In order to increase the rate limits of calling Github APIs, you can input your personal access token.
    Please check the following link for more details about rate limiting:
    https://docs.github.com/en/rest/overview/resources-in-the-rest-api#rate-limiting

    The following link shows how to create your personal access token:
    https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token

    Args:
        bundle_name: bundle name.
        repo: it should be in the form of "repo_owner/repo_name/".
        tag: the tag name of the release.
        auth_token: github personal access token.

    Returns:
        a dictionary that contains the latest version and all versions of a bundle.

    r	  bundle: z is not existing in repo: rl   r   )r   r   r  ro   r
  r  )r  r   rV   r   r  bundle_infor   r?   r?   r@   r     s    r   zdict[str, Any])r  r|   r   rV   r   r9   c                 C  sl   t |||d}| |kr&td|  d||  }|dkrFt| d }||krdtd| d|  d|| S )a  
    Get all information (include "name" and "browser_download_url") of a bundle
    with the specified bundle name and version which is stored in the release of specified repository with the provided tag.
    In order to increase the rate limits of calling Github APIs, you can input your personal access token.
    Please check the following link for more details about rate limiting:
    https://docs.github.com/en/rest/overview/resources-in-the-rest-api#rate-limiting

    The following link shows how to create your personal access token:
    https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token

    Args:
        bundle_name: bundle name.
        version: version name of the target bundle, if None, the latest version will be used.
        repo: it should be in the form of "repo_owner/repo_name/".
        tag: the tag name of the release.
        auth_token: github personal access token.

    Returns:
        a dictionary that contains the bundle's information.

    r	  r  z is not existing.Nr   z	version: z of bundle: r  )r  r|   r   rV   r   r  r  r?   r?   r@   get_bundle_info  s    r  zstr | Sequence[str] | None)
run_idinit_idfinal_id	meta_filer   logging_filetrackingr   overrider9   c           
      K  s4   t f |||||| ||d|}	|	  |	  dS )aF  
    Specify `config_file` to run monai bundle components and workflows.

    Typical usage examples:

    .. code-block:: bash

        # Execute this module as a CLI entry:
        python -m monai.bundle run --meta_file <meta path> --config_file <config path>

        # Execute with specified `run_id=training`:
        python -m monai.bundle run training --meta_file <meta path> --config_file <config path>

        # Execute with all specified `run_id=runtest`, `init_id=inittest`, `final_id=finaltest`:
        python -m monai.bundle run --run_id runtest --init_id inittest --final_id finaltest ...

        # Override config values at runtime by specifying the component id and its new value:
        python -m monai.bundle run --net#input_chns 1 ...

        # Override config values with another config file `/path/to/another.json`:
        python -m monai.bundle run --net %/path/to/another.json ...

        # Override config values with part content of another config file:
        python -m monai.bundle run --net %/data/other.json#net_arg ...

        # Set default args of `run` in a JSON / YAML file, help to record and simplify the command line.
        # Other args still can override the default args at runtime:
        python -m monai.bundle run --args_file "/workspace/data/args.json" --config_file <config path>

    Args:
        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.
        init_id: ID name of the expected config expression to initialize before running, default to "initialize".
            it's optional for both configs and this `run` function.
        final_id: ID name of the expected config expression to finalize after running, default to "finalize".
            it's optional for both configs and this `run` function.
        meta_file: filepath of the metadata file, if it is a list of file paths, the content of them will be merged.
            Default to None.
        config_file: filepath of the config file, if `None`, must be provided in `args_file`.
            if it is a list of file paths, the content of them will be merged.
        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.
            Default to None.
        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 where a set of
            common parameters shown below will be added and can be passed through the `override` parameter of this method.

            - ``"output_dir"``: the path to save mlflow tracking outputs locally, default to "<bundle root>/eval".
            - ``"tracking_uri"``: uri to save mlflow tracking outputs, default to "/output_dir/mlruns".
            - ``"experiment_name"``: experiment name for this run, default to "monai_experiment".
            - ``"run_name"``: the name of current run.
            - ``"save_execute_config"``: whether to save the executed config files. It can be `False`, `/path/to/artifacts`
              or `True`. If set to `True`, will save to the default path "<bundle_root>/eval". Default to `True`.

            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.
        args_file: a JSON or YAML file to provide default values for `run_id`, `meta_file`,
            `config_file`, `logging`, and override pairs. so that the command line inputs can be simplified.
        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  r  r  Nr   runfinalize)
r  r  r  r  r   r  r  r   r  Zworkflowr?   r?   r@   r    s    M	r  )r   r   r8   r9   c                 K  s(   t f | |d|}|  |  dS )a  
    Specify `bundle workflow` to run monai bundle components and workflows.
    The workflow should be subclass of `BundleWorkflow` and be available to import.
    It can be MONAI existing bundle workflows or user customized workflows.

    Typical usage examples:

    .. code-block:: bash

        # Execute this module as a CLI entry with default ConfigWorkflow:
        python -m monai.bundle run_workflow --meta_file <meta path> --config_file <config path>

        # Set the workflow to other customized BundleWorkflow subclass:
        python -m monai.bundle run_workflow --workflow_name CustomizedWorkflow ...

    Args:
        workflow_name: specified bundle workflow name, should be a string or class, default to "ConfigWorkflow".
        args_file: a JSON or YAML file to provide default values for this API.
            so that the command line inputs can be simplified.
        kwargs: arguments to instantiate the workflow class.

    )r   r   Nr  )r   r   r8   	workflow_r?   r?   r@   run_workflow2  s    r  zbool | None)r  r   
create_dirr   	hash_typer   r8   r9   c              
   K  s  t f || ||||d|}td|d t|dddddd	\}}	}
}}t||
d
 tj|	d}|d}|dkrxtdt||||dd tj	|d}zt
f ||d| W nP tk
r } z2ttdtjt|d d| d |W 5 d}~X Y nX td dS )aV  
    Verify the provided `metadata` file based on the predefined `schema`.
    `metadata` content must contain the `schema` field for the URL of schema file to download.
    The schema standard follows: http://json-schema.org/.

    Args:
        meta_file: filepath of the metadata file to verify, if `None`, must be provided in `args_file`.
            if it is a list of file paths, the content of them will be merged.
        filepath: file path to store the downloaded schema.
        create_dir: whether to create directories if not existing, default to `True`.
        hash_val: if not None, define the hash value to verify the downloaded schema file.
        hash_type: if not None, define the hash type to verify the downloaded schema file. Defaults to "md5".
        args_file: a JSON or YAML file to provide default values for all the args in this function.
            so that the command line inputs can be simplified.
        kwargs: other arguments for `jsonschema.validate()`. for more details:
            https://python-jsonschema.readthedocs.io/en/stable/validate/#jsonschema.validate.

    )r6   r  r   r  r   r  verify_metadatar   r   r  TNmd5)r  r   r  )r   r  )filesschemazKmust provide the `schema` field in the metadata for the URL of schema file.)r   r   r   r  r   )r   )instancer"  z.*Failed validatingr   z against schema ``.z#metadata is verified with no error.)rF   r[   rT   r!   r   load_config_filesr.   ro   r   rB   r(   r+   r  r  Sfindallr<   rW   rX   )r  r   r  r   r  r   r8   r   	filepath_
meta_file_Zcreate_dir_Z	hash_val_Z
hash_type_metadatar   r"  er?   r?   r@   r  Q  sF    	     
&r  _meta_#network_data_formatzConfigParser | None)parserr   r9   c           	      C  s   t | tstdt|  d| d}| d}| |}| d}t| |}| d}t| |tj}| d}| d}| |}| d	}t| |tj}|||||fS )
a  
    Get the input and output information defined in the metadata.

    Args:
        parser: a ConfigParser of the given bundle.
        prefix: a prefix for the input and output ID, which will be combined as `prefix#inputs` and
            `prefix#outputs` to parse the input and output information in the `metadata.json` file of
            a bundle, default to `meta_#network_data_format`.

    Returns:
        input_channels: the channel number of the `image` input.
        input_spatial_shape: the spatial shape of the `image` input.
        input_dtype: the data type of the `image` input.
        output_channels: the channel number of the output.
        output_dtype: the data type of the output.
    z/Parameter parser should be a ConfigParser, got rl   z#inputsz#image#num_channelsz#image#spatial_shapez#image#dtypez#outputsz#pred#num_channelsz#pred#dtype)	r;   r   AttributeErrorrq   r.   rC   r$   r   Tensor)	r-  r   Z
prefix_keyr   input_channelsinput_spatial_shapeinput_dtypeoutput_channelsoutput_dtyper?   r?   r@   _get_net_io_info  s    









r5  r   )r-  r9   c                 C  s,   t | d\}}}}}t|}d|f|}|S )z
    Get a fake input shape e.g. [N, C, H, W] or [N, C, H, W, D], whose batch size is 1, from the given parser.

    Args:
        parser: a ConfigParser which contains the i/o information of a bundle.
    r-  re   )r5  rt   )r-  r0  r1  _spatial_shapeinput_shaper?   r?   r@   _get_fake_input_shape  s    r:  z
int | None)net_idr  r   r   rh   ri   rj   extra_forward_argsr   r  r9   c	           "      K  s  t f || |||||||d	|	}
td|
d t|
dddt rBdndd	d	d	i d
	\}}}}}}}}t }|j|d |j|d |
 D ]\}}|||< qt|d\}}}}}z|}|	|
|}W n4 tk
r } ztd| d|W 5 d}~X Y nX |  t  t||||d}tjd	|f|||d}|tjkr|
d ddlm}  |   || f|}!W 5 Q R X |
| n||f|}!|!jd	 |krtd|!jd	  d| d|!j|krtd|!j d| dW 5 Q R X td dS )a  
    Verify the input and output data shape and data type of network defined in the metadata.
    Will test with fake Tensor data according to the required data shape in `metadata`.

    Typical usage examples:

    .. code-block:: bash

        python -m monai.bundle verify_net_in_out network --meta_file <meta path> --config_file <config path>

    Args:
        net_id: ID name of the network component to verify, it must be `torch.nn.Module`.
        meta_file: filepath of the metadata file to get network args, if `None`, must be provided in `args_file`.
            if it is a list of file paths, the content of them will be merged.
        config_file: filepath of the config file to get network definition, if `None`, must be provided in `args_file`.
            if it is a list of file paths, the content of them will be merged.
        device: target device to run the network forward computation, if None, prefer to "cuda" if existing.
        p: power factor to generate fake data shape if dim of expected shape is "x**p", default to 1.
        n: multiply factor to generate fake data shape if dim of expected shape is "x*n", default to 1.
        any: specified size to generate fake data shape if dim of expected shape is "*", default to 1.
        extra_forward_args: a dictionary that contains other args for the forward function of the network.
            Default to an empty dictionary.
        args_file: a JSON or YAML file to provide default values for `net_id`, `meta_file`, `config_file`,
            `device`, `p`, `n`, `any`, and override pairs. so that the command line inputs can be simplified.
        override: id-value pairs to override or add the corresponding config content.
            e.g. ``--_meta#network_data_format#inputs#image#num_channels 3``.

    )	r6   r;  r  r   r   rh   ri   rj   r<  verify_net_in_outr   r   r  r   r   r   re   )r;  r   rh   ri   rj   r<  fr6  z<Failed to verify due to missing expected key in the config: rl   N)rh   ri   rj   )dtyper   cudar   )autocastzoutput channel number `z` doesn't match: `r$  zdtype of output data `z` doesn't match: z0data shape of network is verified with no error.)rF   r[   rT   r   r   read_config	read_metarG   r5  get_parsed_contentr   KeyErrorrp   r   no_gradrt   randfloat16Ztorch.cuda.amprB  rA  rg   ro   r@  rW   rX   )"r;  r  r   r   rh   ri   rj   r<  r   r  r   config_file_r)  net_id_device_p_n_Zany_Zextra_forward_args_r-  rK   rL   r0  r1  r2  r3  r4  r   netr+  r8  	test_datarB  outputr?   r?   r@   r=    sh    )

$

"r=  r
   )		converterr-  r;  r   	ckpt_filer   r   r8   r9   c              	   K  s   | |}tr"tj||i|d n&t|}	t||dkr<|	n|	| d | f d|i|}i }
t|D ]P}tj	
|}tj	|\}}||
krtd| dtt| |
|< qfdd |
 D }
t||d	d	| d
d|
d td| d dS )aa  
    Export a model defined in the parser to a new one specified by the converter.

    Args:
        converter: a callable object that takes a torch.nn.module and kwargs as input and
            converts the module to another type.
        parser: a ConfigParser of the bundle to be converted.
        net_id: ID name of the network component in the parser, it must be `torch.nn.Module`.
        filepath: filepath to export, if filename has no extension, it becomes `.ts`.
        ckpt_file: filepath of the model checkpoint to load.
        config_file: filepath of the config file to save in the converted model,the saved key in the converted
            model is the config filename without extension, and the saved config value is always serialized in
            JSON format no matter the original file format is JSON or YAML. it can be a single file or a list
            of files.
        key_in_ckpt: for nested checkpoint like `{"model": XXX, "optimizer": XXX, ...}`, specify the key of model
            weights. if not nested checkpoint, no need to set.
        kwargs: key arguments for the converter.

    Zto_load
checkpointr   r   r   zFilename part 'z.' is given multiple times in config file list.c                 S  s   i | ]\}}|d  |qS )r   r?   rS   r?   r?   r@   r   [  s      z_export.<locals>.<dictcomp>F_meta_N)jit_objfilename_prefix_or_streaminclude_config_valsappend_timestampmeta_valuesr   zexported to file: rl   )rE  
has_igniter,   load_objectsr   r   r   r#   r   r   basenamesplitextro   r   dumpsr   rB   encoderG   r   r.   rO   rW   rX   )rR  r-  r;  r   rS  r   r   r8   rO  ckptextra_filesrP   rx   r7  r?   r?   r@   _export&  s.    

rd  zSequence[int] | NonezMapping | None)r;  r   rS  r  r   r   	use_tracer9  r   converter_kwargsr  r9   c
                 K  s2  t f || ||||||||	d
|
}td|d t|ddddddd	di d

\	}}}}}}}}}t }|j|d |dk	r|j|d | D ]\}}|||< q|st|d}t	|g}|
|}trtj||i|d n&t|}t||dkr|n|| d |||d tf d|i|}t|| dS )a  
    Export the model checkpoint to an onnx model.

    Typical usage examples:

    .. code-block:: bash

        python -m monai.bundle onnx_export network --filepath <export path> --ckpt_file <checkpoint path> ...

    Args:
        net_id: ID name of the network component in the config, it must be `torch.nn.Module`.
        filepath: filepath where the onnx model is saved to.
        ckpt_file: filepath of the model checkpoint to load.
        meta_file: filepath of the metadata file, if it is a list of file paths, the content of them will be merged.
        config_file: filepath of the config file that contains extract network information,
        key_in_ckpt: for nested checkpoint like `{"model": XXX, "optimizer": XXX, ...}`, specify the key of model
            weights. if not nested checkpoint, no need to set.
        use_trace: whether using `torch.jit.trace` to convert the pytorch model to torchscript model.
        input_shape: a shape used to generate the random input of the network, when converting the model to an
            onnx model. Should be a list like [N, C, H, W] or [N, C, H, W, D]. If not given, will try to parse from
            the `metadata` config.
        args_file: a JSON or YAML file to provide default values for all the parameters of this function, so that
            the command line inputs can be simplified.
        converter_kwargs: extra arguments that are needed by `convert_to_onnx`, except ones that already exist in the
            input parameters.
        override: id-value pairs to override or add the corresponding config content.
            e.g. ``--_meta#network_data_format#inputs#image#num_channels 3``.

    
r6   r;  r   r  r   rS  r   re  r9  rf  onnx_exportr   r   rS  r   r   NF)r;  r  r   re  r9  rf  r>  r6  rT  r   inputsre  r   )rF   r[   rT   r   rC  rD  rG   r:  r   rH  rE  r\  r,   r]  r   r   updater   r/   save)r;  r   rS  r  r   r   re  r9  r   rf  r  r   r(  
ckpt_file_rJ  rK  r)  key_in_ckpt_
use_trace_input_shape_converter_kwargs_r-  rK   rL   inputs_rO  rb  
onnx_modelr?   r?   r@   rh  h  sl    *



rh  c
                 K  s  t f || ||||||||	d
|
}td|d t|ddddddddi d
\	}}}}}}}}}|d	t }t }|j|d
 |dkrtj	|ddn|}tj
|r|j|d
 | D ]\}}|||< q|dkrtj	|ddn|}|dkrtj	|ddn|}tj
|s&td| d|dkr4dn|}z|| W n< tk
r } ztd| d| d|W 5 d}~X Y nX |s|rt|d}|rt|gnd}|||d tt|f|||||d| dS )a	  
    Export the model checkpoint to the given filepath with metadata and config included as JSON files.

    Typical usage examples:

    .. code-block:: bash

        python -m monai.bundle ckpt_export network --filepath <export path> --ckpt_file <checkpoint path> ...

    Args:
        net_id: ID name of the network component in the config, it must be `torch.nn.Module`.
            Default to "network_def".
        filepath: filepath to export, if filename has no extension it becomes `.ts`.
            Default to "models/model.ts" under "os.getcwd()" if `bundle_root` is not specified.
        ckpt_file: filepath of the model checkpoint to load.
            Default to "models/model.pt" under "os.getcwd()" if `bundle_root` is not specified.
        meta_file: filepath of the metadata file, if it is a list of file paths, the content of them will be merged.
            Default to "configs/metadata.json" under "os.getcwd()" if `bundle_root` is not specified.
        config_file: filepath of the config file to save in TorchScript model and extract network information,
            the saved key in the TorchScript model is the config filename without extension, and the saved config
            value is always serialized in JSON format no matter the original file format is JSON or YAML.
            it can be a single file or a list of files. if `None`, must be provided in `args_file`.
        key_in_ckpt: for nested checkpoint like `{"model": XXX, "optimizer": XXX, ...}`, specify the key of model
            weights. if not nested checkpoint, no need to set.
        use_trace: whether using `torch.jit.trace` to convert the PyTorch model to TorchScript model.
        input_shape: a shape used to generate the random input of the network, when converting the model to a
            TorchScript model. Should be a list like [N, C, H, W] or [N, C, H, W, D]. If not given, will try to
            parse from the `metadata` config.
        args_file: a JSON or YAML file to provide default values for all the parameters of this function, so that
            the command line inputs can be simplified.
        converter_kwargs: extra arguments that are needed by `convert_to_torchscript`, except ones that already exist
            in the input parameters.
        override: id-value pairs to override or add the corresponding config content.
            e.g. ``--_meta#network_data_format#inputs#image#num_channels 3``.

    rg  ckpt_exportr   r   Nr   F)r   rS  r;  r  r   re  r9  rf  bundle_rootr>  r   metadata.jsonr   r   r   zCheckpoint file "z7" not found, please specify it in argument "ckpt_file".r   zNetwork definition "z" cannot be found in "z'", specify name with argument "net_id".r6  ri  r;  r   rS  r   r   )rF   r[   rT   r.   r   getcwdr   rC  r   r   r   rD  rG   FileNotFoundErrorrE  ro   r:  r   rH  rk  rd  r   )r;  r   rS  r  r   r   re  r9  r   rf  r  r   rJ  r(  rm  rK  r)  rn  ro  rp  rq  ru  r-  rK   rL   r+  rr  r?   r?   r@   rt    s    1

rt  zSequence[str] | None)r;  r   rS  r  r   r   	precisionr9  re  dynamic_batchsizer   use_onnxonnx_input_namesonnx_output_namesr   rf  r  r9   c           %      K  s  t f || |||||||||	|
||||d|}td|d t|ddddddd	g d
ddd
dgdgi d\}}}}}}}}}}}}}}} t }!|!j|d |dk	r|!j|d | D ]\}"}#|#|!|"< q|st|!d}||||||||d}$| |$ t	t
|!f|||||d|  dS )a  
    Export the model checkpoint to the given filepath as a TensorRT engine-based TorchScript.
    Currently, this API only supports converting models whose inputs are all tensors.

    There are two ways to export a model:
    1, Torch-TensorRT way: PyTorch module ---> TorchScript module ---> TensorRT engine-based TorchScript.
    2, ONNX-TensorRT way: PyTorch module ---> TorchScript module ---> ONNX model ---> TensorRT engine --->
    TensorRT engine-based TorchScript.

    When exporting through the first way, some models suffer from the slowdown problem, since Torch-TensorRT
    may only convert a little part of the PyTorch model to the TensorRT engine. However when exporting through
    the second way, some Python data structures like `dict` are not supported. And some TorchScript models are
    not supported by the ONNX if exported through `torch.jit.script`.

    Typical usage examples:

    .. code-block:: bash

        python -m monai.bundle trt_export --net_id <network definition> --filepath <export path>             --ckpt_file <checkpoint path> --input_shape <input shape> --dynamic_batchsize <batch range> ...

    Args:
        net_id: ID name of the network component in the config, it must be `torch.nn.Module`.
        filepath: filepath to export, if filename has no extension, it becomes `.ts`.
        ckpt_file: filepath of the model checkpoint to load.
        meta_file: filepath of the metadata file, if it is a list of file paths, the content of them will be merged.
        config_file: filepath of the config file to save in the TensorRT based TorchScript model and extract network
            information, the saved key in the model is the config filename without extension, and the saved config
            value is always serialized in JSON format no matter the original file format is JSON or YAML.
            it can be a single file or a list of files. if `None`, must be provided in `args_file`.
        key_in_ckpt: for nested checkpoint like `{"model": XXX, "optimizer": XXX, ...}`, specify the key of model
            weights. if not nested checkpoint, no need to set.
        precision: the weight precision of the converted TensorRT engine based TorchScript models. Should be 'fp32' or 'fp16'.
        input_shape: the input shape that is used to convert the model. Should be a list like [N, C, H, W] or
            [N, C, H, W, D]. If not given, will try to parse from the `metadata` config.
        use_trace: whether using `torch.jit.trace` to convert the PyTorch model to a TorchScript model and then convert to
            a TensorRT engine based TorchScript model or an ONNX model (if `use_onnx` is True).
        dynamic_batchsize: a sequence with three elements to define the batch size range of the input for the model to be
            converted. Should be a sequence like [MIN_BATCH, OPT_BATCH, MAX_BATCH]. After converted, the batchsize of
            model input should between `MIN_BATCH` and `MAX_BATCH` and the `OPT_BATCH` is the best performance batchsize
            that the TensorRT tries to fit. The `OPT_BATCH` should be the most frequently used input batchsize in
            the application.
        device: the target GPU index to convert and verify the model.
        use_onnx: whether using the ONNX-TensorRT way to export the TensorRT engine-based TorchScript model.
        onnx_input_names: optional input names of the ONNX model. This arg is only useful when `use_onnx` is True. Should be
            a sequence like `['input_0', 'input_1', ..., 'input_N']` where N equals to the number of the model inputs. If not
            given, will use `['input_0']`, which supposes the model only has one input.
        onnx_output_names: optional output names of the ONNX model. This arg is only useful when `use_onnx` is True. Should be
            a sequence like `['output_0', 'output_1', ..., 'output_N']` where N equals to the number of the model outputs. If
            not given, will use `['output_0']`, which supposes the model only has one output.
        args_file: a JSON or YAML file to provide default values for all the parameters of this function, so that
            the command line inputs can be simplified.
        converter_kwargs: extra arguments that are needed by `convert_to_trt`, except ones that already exist in the
            input parameters.
        override: id-value pairs to override or add the corresponding config content.
            e.g. ``--_meta#network_data_format#inputs#image#num_channels 3``.

    )r6   r;  r   r  r   rS  r   rz  r9  re  r{  r   r|  r}  r~  rf  
trt_exportr   r   rS  r   r   Nfp32Finput_0output_0)r;  r  r   rz  r9  re  r{  r   r|  r}  r~  rf  r>  r6  )rz  r9  r{  re  r   r|  r}  r~  rw  )rF   r[   rT   r   rC  rD  rG   r:  rk  rd  r   )%r;  r   rS  r  r   r   rz  r9  re  r{  r   r|  r}  r~  r   rf  r  r   r(  rm  rJ  rK  r)  rn  Z
precision_rp  ro  Zdynamic_batchsize_rL  Z	use_onnx_Zonnx_input_names_Zonnx_output_names_rq  r-  rK   rL   Ztrt_api_parametersr?   r?   r@   r  V  s    M



r  r   zdict | str | None)r   rS  networkdataset_licensemetadata_strinference_strr9   c              	   C  s  |dkrt }|dkrt}t|  } |  r@tdt|  d| j s^tdt|  d| d }| d }| d }| 	  |	  |	  |	  t
|trtj|d	d
}t
|trtj|d	d
}tt|d d}	|	| W 5 Q R X tt|d d}	|	| W 5 Q R X tt|d d}	d}
|	t|
 W 5 Q R X tt| d d}	|	d W 5 Q R X |dkrtt|d d}	|	d W 5 Q R X |dk	rtt|t|d  n|dk	rt|t|d  dS )a  
    Initialise a new bundle directory with some default configuration files and optionally network weights.

    Typical usage example:

    .. code-block:: bash

        python -m monai.bundle init_bundle /path/to/bundle_dir network_ckpt.pt

    Args:
        bundle_dir: directory name to create, must not exist but parent direct must exist
        ckpt_file: optional checkpoint file to copy into bundle
        network: if given instead of ckpt_file this network's weights will be stored in bundle
        dataset_license: if `True`, a default license file called "data_license.txt" will be produced. This
            file is required if there are any license conditions stated for data your bundle uses.
        metadata_str: optional metadata string to write to bundle, if not given a default will be used.
        inference_str: optional inference string to write to bundle, if not given a default will be used.
    NzSpecified bundle directory 'z' already existsz0Parent directory of specified bundle directory 'z' does not existr   r   docs   )indentrv  wzinference.json	README.mda  
        # Your Model Name

        Describe your model here and how to run it, for example using `inference.json`:

        ```
        python -m monai.bundle run             --meta_file /path/to/bundle/configs/metadata.json             --config_file /path/to/bundle/configs/inference.json             --dataset_dir ./input             --bundle_root /path/to/bundle
        ```
        LICENSEz*Select a license and place its terms here
Tzdata_license.txtz6Select a license for dataset and place its terms here
r   )r   r   r   absoluter   ro   r<   parentis_dirmkdirr;   r5   r   r`  openwriter   r   r    )r   rS  r  r  r  r  Zconfigs_dirZ
models_dirZdocs_diroreadmer?   r?   r@   init_bundle  sH    





r  c              	   C  s   d}t jt j| d}t j|rdt|}| }W 5 Q R X d|krXd|krXd}nd|krdd}d}d	| d
| d}t| }| }W 5 Q R X |d | }t| d}|| W 5 Q R X d S )Nunknownr  zApache LicensezVersion 2.0z
apache-2.0zMIT LicenseZmitz&- monai
- medical
library_name: monai
z
---
tags:
z	license: z
---
r  )r   r   r   dirnamer   r  readr  )new_modelcard_pathZlicense_nameZlicense_pathfilecontentr   Ztag_contentZnew_contentr?   r?   r@   _add_model_card_metadata[  s     

r  )	r   r*   r   tokenprivater|   tag_as_latest_versionupload_folder_kwargsr9   c                 K  s   t j|d}|j| |dd tj||d}	tj||dd}
tj|
r\t|
|	 t|	 |j	f | tj||d|}|dk	r|j
| |dd |r|j
| d	dd |S )
af  
    Push a MONAI bundle to the Hugging Face Hub.

    Typical usage examples:

    .. code-block:: bash

        python -m monai.bundle push_to_hf_hub --repo <HF repository id> --name <bundle name>             --bundle_dir <bundle directory> --version <version> ...

    Args:
        repo: namespace (user or organization) and a repo name separated by a /, e.g. `hf_username/bundle_name`
        bundle_name: name of the bundle directory to push.
        bundle_dir: path to the bundle directory.
        token: Hugging Face authentication token. Default is `None` (will default to the stored token).
        private: Private visibility of the repository on Hugging Face. Default is `True`.
        version_name: Name of the version tag to create. Default is `None` (no version tag is created).
        tag_as_latest_version: Whether to tag the commit as `latest_version`.
            This version will downloaded by default when using `bundle.download()`. Default is `False`.
        upload_folder_kwargs: Keyword arguments to pass to `HfApi.upload_folder`.

    Returns:
        repo_url: URL of the Hugging Face repo
    )r  T)r   r  exist_okr  r  )r   folder_pathN)r   rV   r  r   )r0   HfApicreate_repor   r   r   r   r   r  upload_folder
create_tag)r   r*   r   r  r  r|   r  r  hf_apir  Zmodelcard_pathZrepo_urlr?   r?   r@   push_to_hf_hubs  s    #
 r  )r   r   r   r8   r9   c                 K  s   t f || |d|}td|d t|tdd\} }t| tr|tdt| d\}}|sbtt| }|dkrtd|  d	n t	| t
r| }ntd
|  d	|dk	r|f d|i|}n
|f |}|  |S )a2  
    Specify `bundle workflow` to create monai bundle workflows.
    The workflow should be subclass of `BundleWorkflow` and be available to import.
    It can be MONAI existing bundle workflows or user customized workflows.

    Typical usage examples:

    .. code-block:: python

        # Specify config_file path to create workflow:
        workflow = create_workflow(config_file="/workspace/spleen_ct_segmentation/configs/train.json", workflow_type="train")

        # Set the workflow to other customized BundleWorkflow subclass to create workflow:
        workflow = create_workflow(workflow_name=CustomizedWorkflow)

    Args:
        workflow_name: specified bundle workflow name, should be a string or class, default to "ConfigWorkflow".
        config_file: filepath of the config file, if it is a list of file paths, the content of them will be merged.
        args_file: a JSON or YAML file to provide default values for this API.
            so that the command line inputs can be simplified.
        kwargs: arguments to instantiate the workflow class.

    )r6   r   r   r  r   N)r   r   zmonai.bundler)   z(cannot locate specified workflow class: rl   zaArgument `workflow_name` must be a bundle workflow class nameor subclass of BundleWorkflow, got: r   )rF   r[   rT   r   r;   r<   r&   r   ro   
issubclassr   
initialize)r   r   r   r8   r   Zworkflow_classhas_built_inr  r?   r?   r@   r     s.      




r   )bundle_pathlarge_file_namer9   c                 C  s   | dkrt  n| } |dkr\tt| d}ttdd |}t|dkr\td|  dt }|	| |
 d }|D ]z}d	|d
< d|kr|
dddkr|d d|kr|
dddkr|d t j| |d |d< |d tf | q|dS )a  
    This utility allows you to download large files from a bundle. It supports file suffixes like ".yml", ".yaml", and ".json".
    If you don't specify a `large_file_name`, it will automatically search for large files among the supported suffixes.

    Typical usage examples:
    .. code-block:: bash

        # Execute this module as a CLI entry to download large files from a bundle path:
        python -m monai.bundle download_large_files --bundle_path <bundle_path>

        # Execute this module as a CLI entry to download large files from the bundle path with a specified `large_file_name`:
        python -m monai.bundle download_large_files --bundle_path <bundle_path> --large_file_name large_files.yaml

    Args:
        bundle_path: (Optional) The path to the bundle where the files are located. Default is `os.getcwd()`.
        large_file_name: (Optional) The name of the large file to be downloaded.

    Nzlarge_files*c                 S  s
   | j dkS )N)z.ymlz.yamlr   )suffix)r>   r?   r?   r@   <lambda>      z&download_large_files.<locals>.<lambda>r   z0Cannot find the large_files.yml/yaml/json under rl   Zlarge_filesTfuzzyr   r   r  r   r   )r   rx  rD   r   globfilterr   ry  r   rC  r.   rO   r   r   r   )r  r  Zlarge_file_pathr-  Zlarge_files_listZlf_datar?   r?   r@   download_large_files  s$    



r  )NT)re   re   re   )T)r   )r   )N)r   r   N)r   r   N)r   r   N)Nr   r   N)NNNNNNNN)NN)NNNNNN)Nr,  )	NNNNNNNNN)
NNNNNNNNNN)
NNNNNNNNNN)NNNNNNNNNNNNNNNN)NNFNN)NTNF)NNN)NN)t
__future__r   r]   r   r   r  r   collections.abcr   r   pathlibr   pydocr   shutilr   textwrapr   typingr	   r
   r   
torch.cudar   Zmonai.apps.mmars.mmarsr   monai.apps.utilsr   r   r   r   Zmonai.bundle.config_itemr   monai.bundle.config_parserr   monai.bundle.utilsr   r   Zmonai.bundle.workflowsr   r   monai.configr   r   
monai.datar   r   monai.networksr   r   r   r   r   r    monai.utilsr!   r"   r#   r$   r%   r&   r'   r(   r7  r+   OPT_IMPORT_VERSIONr,   r\  r   r   r/   r0   __name__rW   environr.   ZDEFAULT_DOWNLOAD_SOURCErY   rF   _update_argsrT   r[   rd   rt   rz   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r   r  r  r  r  r5  r:  r=  rd  rh  rt  r  r  r  r  r   r  r?   r?   r?   r@   <module>   s~   $

%
" @ %     -     #     $    *        "]          =%         $fC          &m          &                 2 .     Z     =   :