o
    iN3                     @  s"  d Z ddlmZ ddlZddlZddlZddlmZ ddlm	Z	 ddl
mZ ddlZddlm  m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 g dZd@ddZdAddZ dBdCddZ!dBdDdd Z"	"dEdFd,d-Z#		!	"		!	.	/	!	dGdHd8d9Z$dIdJd>d?Z%dS )Kzr
Utilities for accessing Nvidia MMARs

See Also:
    - https://docs.nvidia.com/clara/clara-train-sdk/pt/mmar.html
    )annotationsN)Mapping)Path)Any)download_and_extractlogger)PathLike)copy_model_state)optional_import   )
MODEL_DESC)RemoteMMARKeys)get_model_specdownload_mmarload_from_mmaridx	int | strreturn
dict | Anyc                 C  sZ   t | tr	t|  S t | tr+|   }tD ]}t|tj  |kr*|  S q| S )zlget model specification by `idx`. `idx` could be index of the constant tuple of dict or the actual model ID.)	
isinstanceintr   strstriplowergetKeysID)r   keycand r   X/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/apps/mmars/mmars.pyr   )   s   

r   2   c                 C  s
  d}ddddgg dg ddd	}t d
d|  ddg}||d< ||d< ||d< t|}| d| }tddd\}}	|	rH||}
|
  ntdt|
j}i }|d D ]*}|d D ]#}|d }d
|d
 i||< |d D ]}|d dkr|d || d< qpq^qX|S )Nz<https://api.ngc.nvidia.com/v2/search/catalog/resources/MODEL scoreDESC)fieldvalue)alldescriptiondisplayNamename
resourceId)
ZisPublic
attributesZguestAccessr*   ZorgNameZteamNamer)   ZdateModifiedlabelsr(   r   )queryZorderByZqueryFieldsfieldspager*   *r0   ZpageSizefiltersz?q=requestsr   r*   z6NGC API requires requests package.  Please install it.results	resourcesr+   r,   r   ZlatestVersionIdStrr&   latest)dictjsondumpsr
   raise_for_status
ValueErrorloadstext)patternZ
page_index	page_sizeurl
query_dictfilterZ	query_strfull_urlrequests_gethas_requestsresp
model_list
model_dictresultmodelZcurrent_res_id	attributer   r   r    _get_all_ngc_models5   s>   


rM   r"   
model_namer   versionmodel_prefixc                 C  s   d| |  d| dS )Nz%https://api.ngc.nvidia.com/v2/models/z
/versions/z/zipr   )rN   rO   rP   r   r   r    _get_ngc_urlb   s   rQ   c                 C  s   d| |  S )Nz&https://ngc.nvidia.com/catalog/models/r   )rN   rP   r   r   r    _get_ngc_doc_urlf   s   rR   Titemstr | Mappingmmar_dirPathLike | Noneprogressboolapir   r   c                 C  s  |st ddd\}}|rt| d }ntdt|}|rtt| tr,| tj|  n|  }t	|dkr>td|  dg }	|
 D ]6\}
}|d	krP|d
 nt|}t|
|}||d  }t|||d  d| d |dddd|d |	| qD|	std|  d|	d S t| tst| } | tjd}|dkrt|}| tj  d| }|| }| tjpt| tj |dd}t||| d| tj   || tj | tj | tj d|d |S )a'  
    Download and extract Medical Model Archive (MMAR) from Nvidia Clara Train.

    See Also:
        - https://docs.nvidia.com/clara/
        - Nvidia NGC Registry CLI
        - https://docs.nvidia.com/clara/clara-train-sdk/pt/mmar.html

    Args:
        item: the corresponding model item from `MODEL_DESC`.
          Or when api is True, the substring to query NGC's model name field.
        mmar_dir: target directory to store the MMAR, default is `mmars` subfolder under `torch.hub get_dir()`.
        progress: whether to display a progress bar.
        api: whether to query NGC and download via api
        version: which version of MMAR to download.  -1 means the latest from ngc.

    Examples::
        >>> from monai.apps import download_mmar
        >>> download_mmar("clara_pt_prostate_mri_segmentation_1", mmar_dir=".")
        >>> download_mmar("prostate_mri_segmentation", mmar_dir=".", api=True)


    Returns:
        The local directory of the downloaded model.
        If api is True, a list of local directories of downloaded models.
    z	torch.hubget_dirr4   mmarszTmmar_dir=None, but no suitable default directory computed. Upgrade Pytorch to 1.6+ ?r   z&api query returns no item for pattern z.  Please change or shorten it.rS   r7   r*   _z.zipNmd5zipF)rA   filepath
output_dirhash_val	hash_type	file_typehas_baserX   z'api query download no item for pattern r   znvidia/med/)rO   rP   .)r
   r   r<   rM   r   r   r   r   NAMElenitemsr   rQ   r   appendr   VERSIONZURLZ	FILE_TYPEZHASH_VALZ	HASH_TYPE)rT   rV   rX   rZ   rO   r[   Zhas_homeZ	_mmar_dirrI   Zmodel_dir_listkvverdownload_url	model_dirZmodel_fullnameZ	model_urlr   r   r    r   j   s`   $


 
r   FrK   Mapping | str | intmap_location
Any | None
pretrainedweights_only	model_key
model_filer   c
                 C  s   |rt jt| trt| t j n|  i} t| tst| } t| ||||d}
|	du r1tj	dd}	|
| 
t j|	 }td| 
t j d|
 d |jdrf|sWtd	 |r^td
 tjj||dS tj||dd}|rv|
||S tt|
di |i d}|rt|ts|
| 
t jtj	dd }t|}t|}W d   n1 sw   Y  t|}t||i d}|stt||i d}|rt|tstd| 
t j d| 
t j d|
dr|d }tj| }n5|
dr|
dddd\}}t||d\}}|std|
dd d|
 dntd| dtd|  |
dd}|rF|d(i |}td|  n| }|rpt||
||dd \}}}|r`|rpt d!t!| d"t!| d td# | 
t j"pt#| t j d$d%}td&| d' |S ))ak  
    Download and extract Medical Model Archive (MMAR) model weights from Nvidia Clara Train.

    Args:
        item: the corresponding model item from `MODEL_DESC`.
        mmar_dir: : target directory to store the MMAR, default is mmars subfolder under `torch.hub get_dir()`.
        progress: whether to display a progress bar when downloading the content.
        version: version number of the MMAR. Set it to `-1` to use `item[Keys.VERSION]`.
        map_location: pytorch API parameter for `torch.load` or `torch.jit.load`.
        pretrained: whether to load the pretrained weights after initializing a network module.
        weights_only: whether to load only the weights instead of initializing the network module and assign weights.
        model_key: a key to search in the model file or config file for the model dictionary.
            Currently this function assumes that the model dictionary has
            `{"[name|path]": "test.module", "args": {'kw': 'test'}}`.
        api: whether to query NGC API to get model infomation.
        model_file: the relative path to the model file within an MMAR.

    Examples::
        >>> from monai.apps import load_from_mmar
        >>> unet_model = load_from_mmar("clara_pt_prostate_mri_segmentation_1", mmar_dir=".", map_location="cpu")
        >>> print(unet_model)

    See Also:
        https://docs.nvidia.com/clara/
    )rT   rV   rX   rO   rZ   Nmodelszmodel.ptz
*** "z" available at rf   z.tsz4Loading a ScriptModule, 'pretrained' option ignored.z6Loading a ScriptModule, 'weights_only' option ignored.)rr   T)rr   ru   Z
train_confr   defaultconfigzconfig_train.jsonz4Could not load model config dictionary from config: z, or from model file: r*   pathr   )moduler*   z!Could not load MMAR model config r"   z*, Please make sure MMAR's sub-folders in 'z[' is on the PYTHONPATH.See also: https://docs.nvidia.com/clara/clara-train-sdk/pt/byom.htmlzCould not load model config z*** Model: argsz*** Model params: )inplacez&*** Loading model state -- unchanged: z, changed: z
---znvidia:med:)rP   z#For more information, please visit 
r   )$r   rg   r   r   r   r   r   osr|   joinr   Z
MODEL_FILEr   infor*   endswithwarningswarntorchjitload_get_valr8   ZCONFIG_FILEopenr9   r<   
monai_nets__dict__rsplitr
   r	   warningrh   ZDOCrR   )rT   rV   rX   rO   rr   rt   ru   rv   rZ   rw   rp   Z_model_filerI   Zmodel_configZ	json_pathf	conf_dictrN   Z	model_clsZmodel_moduleZhas_clsZmodel_kwargsZ
model_instr]   changedZ	unchangedZdoc_urlr   r   r    r      s|   %$
 




 
 r   
input_dictr   r   rz   c                 C  sN   || v r| | S | D ]}| | }t |tr$t||dd}|dur$|  S q
|S )z
    Search for the item with `key` in `config_dict`.
    Returns: the first occurrence of `key` in a breadth first search.
    Nry   )r   r   r   )r   r   rz   Zsub_dictvalZ	found_valr   r   r    r   -  s   
r   )r   r   r   r   )r   r!   )r"   )rN   r   rO   r   rP   r   r   r   )rN   r   rP   r   r   r   )NTTrS   )rT   rU   rV   rW   rX   rY   rZ   rY   rO   r   r   r   )	NTrS   NTFrK   TN)rT   rq   rV   rW   rX   rY   rO   r   rr   rs   rt   rY   ru   rY   rv   r   rZ   rY   rw   rW   r   r   )rK   N)r   r   r   r   rz   rs   r   rs   )&__doc__
__future__r   r9   r   r   collections.abcr   pathlibr   typingr   r   monai.networks.netsnetworksnetsr   monai.apps.utilsr   r   monai.config.type_definitionsr   monai.networks.utilsr	   monai.utils.moduler
   
model_descr   r   r   __all__r   rM   rQ   rR   r   r   r   r   r   r   r    <module>   sD   


-Tq