U
    Pht8                     @  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Zd dlZd dl	Z	d dl
Z
d dlZd dlmZ d dlmZmZ d dlmZmZmZ d dlmZ d dlmZmZ d dlmZ d d	lmZmZmZ ed
d\Z Z!erd dl"m"Z" dZ#nedded\Z"Z#ddddddgZ$dZ%ej&ej'ej(ej)dZ*de%ddfddddddddZ+e+dZ,e$-d d dd!d"d#Z.d6dd$d%d&d'd(d)Z/d7d ddd%d+d,dZ0d8dd ddd%d.d&d/d0dZ1d9d d dddd%d&d2d3dZ2d:dd d dddd%d%d&d4	d5dZ3dS );    )annotationsN)Path)TYPE_CHECKINGAny)ContentTooShortError	HTTPErrorURLError)urlparse)urlopenurlretrieve)PathLike)look_up_optionmin_versionoptional_importgdownz4.7.3)tqdmTr   z4.47.0
check_hashdownload_url
extractalldownload_and_extract
get_loggerSUPPORTED_HASH_TYPESz)%(asctime)s - %(levelname)s - %(message)s)md5sha1sha256sha512z
monai.appsstrz
str | Nonezlogging.Handler | Nonezlogging.Logger)module_namefmtdatefmtlogger_handlerreturnc                 C  sz   | dk	o| t jjjk}t | }d|_|t j |rdt t	j
}t j||d}|| || |dk	rv|| |S )a  
    Get a `module_name` logger with the specified format and date format.
    By default, the logger will print to `stdout` at the INFO level.
    If `module_name` is `None`, return the root logger.
    `fmt` and `datafmt` are passed to a `logging.Formatter` object
    (https://docs.python.org/3/library/logging.html#formatter-objects).
    `logger_handler` can be used to add an additional handler.
    NF)r   r   )loggingrootmanager
loggerDict	getLogger	propagatesetLevelINFOStreamHandlersysstdout	FormattersetFormatter
addHandler)r   r   r   r    Zadds_stdout_handlerloggerhandler	formatter r3   E/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/apps/utils.pyr   0   s    



r0   r   )pr!   c                 C  s*   t jjt jjpd d }t|  |jS )zHget the last part of the path (removing the trailing slash if it exists) z/ )ospathsepaltsepr   rstripname)r5   r9   r3   r3   r4   	_basenameQ   s    r=   r   boolNone)urlfilepathprogressr!   c                 C  s   zlt rN|rNG dd dt}|ddddt|d}t| ||jd W 5 Q R X nt s`|r`td	 t| | W nF ttt	t
fk
r } z td
|  d| d |W 5 d}~X Y nX dS )zT
    Retrieve file from `url` to `filepath`, optionally showing a progress bar.
    c                   @  s&   e Zd ZdZd
ddddddd	ZdS )z)_download_with_progress.<locals>.TqdmUpToz
                Provides `update_to(n)` which uses `tqdm.update(delta_n)`.
                Inspired by the example in https://github.com/tqdm/tqdm.
                   Nintz
int | Noner?   )bbsizetsizer!   c                 S  s&   |dk	r|| _ | || | j  dS )a!  
                    Args:
                        b: number of blocks transferred so far, default: 1.
                        bsize: size of each block (in tqdm units), default: 1.
                        tsize: total size (in tqdm units). if None, remains unchanged.
                    N)totalupdaten)selfrE   rF   rG   r3   r3   r4   	update_tod   s    z3_download_with_progress.<locals>.TqdmUpTo.update_to)rC   rC   N)__name__
__module____qualname____doc__rL   r3   r3   r3   r4   TqdmUpTo^   s   rQ   BTi   rC   )unit
unit_scaleunit_divisorminitersdesc)
reporthookzBtqdm is not installed, will not show the downloading progress bar.zDownload failed from  to .N)has_tqdmr   r=   r   rL   warningswarnr   r   r   OSErrorr0   error)r@   rA   rB   rQ   ter3   r3   r4   _download_with_progressW   s    
rb   r   )rA   val	hash_typer!   c              
     s  |dkr*t d| d| d|  d dS t| t}tjdkrN|dd	}n| }z<t| d
( t fdddD ]}|	| qtW 5 Q R X W n8 t
k
r } zt d|  W Y dS d}~X Y nX || krt d|  d dS t dt|  d| d| d dS )a  
    Verify hash signature of specified file.

    Args:
        filepath: path of source file to verify hash value.
        val: expected hash value of the file.
        hash_type: type of hash algorithm to use, default is `"md5"`.
            The supported hash types are `"md5"`, `"sha1"`, `"sha256"`, `"sha512"`.
            See also: :py:data:`monai.apps.utils.SUPPORTED_HASH_TYPES`.

    Nz	Expected z is None, skip z check for file rZ   T)   	   F)usedforsecurityrbc                     s
     dS )Ni   )readr3   fr3   r4   <lambda>       zcheck_hash.<locals>.<lambda>rm   zException in check_hash: zcheck_hash failed z
Verified 'z', z: )r0   infor   lowerr   r+   version_infoopeniterrI   	Exceptionr_   	hexdigestr=   )rA   rc   rd   Zactual_hash_funcZactual_hashchunkra   r3   rj   r4   r   z   s&    
"r6   r   )r@   rA   hash_valrd   rB   gdown_kwargsr!   c                 K  s   |s(t dt|  }td| d t |}| rzt|||sdt| d| d| d| dtd| d d	S z@t	 ,}t |t|}t
| jd
krtstdd|krd|d< tj| | fd| i| nt
| jdkrXt| X}| }	|	dkr*t|d }
t|
||d n"td|
 d|  dd| d W 5 Q R X nt| ||d | std|  d| d|j}|rtj|dd t| |  W 5 Q R X W n ttfk
r   Y nX td|  t|||st| d|  d| d| d| d
d	S )a*  
    Download file from specified URL link, support process bar and hash check.

    Args:
        url: source URL link to download file.
        filepath: target filepath to save the downloaded file (including the filename).
            If undefined, `os.path.basename(url)` will be used.
        hash_val: expected hash value to validate the downloaded file.
            if None, skip hash validation.
        hash_type: 'md5' or 'sha1', defaults to 'md5'.
        progress: whether to display a progress bar.
        gdown_kwargs: other args for `gdown` except for the `url`, `output` and `quiet`.
            these args will only be used if download from google drive.
            details of the args of it:
            https://github.com/wkentaro/gdown/blob/main/gdown/download.py

    Raises:
        RuntimeError: When the hash validation of the ``filepath`` existing file fails.
        RuntimeError: When a network issue or denied permission prevents the
            file download from ``url`` to ``filepath``.
        URLError: See urllib.request.urlretrieve.
        HTTPError: See urllib.request.urlretrieve.
        ContentTooShortError: See urllib.request.urlretrieve.
        IOError: See urllib.request.urlretrieve.
        RuntimeError: When the hash validation of the ``url`` downloaded file fails.

    rZ   zDefault downloading to ''z) check of existing file failed: filepath=, expected =zFile exists: z, skipped downloading.Nzdrive.google.comzITo download files from Google Drive, please install the gdown dependency.fuzzyTquietzcloud-api.yandex.net   href)rB   zDownload of file from z, received from  rY   z2 failed due to network issue or denied permission.)exist_okzDownloaded: z& check of downloaded file failed: URL=z, filepath=)r   r=   resolver0   rn   existsr   RuntimeErrortempfileTemporaryDirectoryr	   netloc	has_gdownr   downloadr
   getcodejsonloadrb   parentr7   makedirsshutilmovePermissionErrorNotADirectoryError)r@   rA   rv   rd   rB   rw   tmp_dirtmp_nameresponsecoder   Zfile_dirr3   r3   r4   r      s^    #



 rZ   )rA   
output_dirrv   rd   	file_typehas_baser!   c           
   	   C  s@  |rt |t| dd }nt |}| rVt| ddk	rVtd| d dS t | } |rt| ||st	| d|  d| d| dtd	| d |
  }| jd
s|d
krt| }|| |  dS | jds| jdsd|kr&t| }	|	| |	  dS td|  d| ddS )aK  
    Extract file to the output directory.
    Expected file types are: `zip`, `tar.gz` and `tar`.

    Args:
        filepath: the file path of compressed file.
        output_dir: target directory to save extracted files.
        hash_val: expected hash value to validate the compressed file.
            if None, skip hash validation.
        hash_type: 'md5' or 'sha1', defaults to 'md5'.
        file_type: string of file type for decompressing. Leave it empty to infer the type from the filepath basename.
        has_base: whether the extracted files have a base folder. This flag is used when checking if the existing
            folder is a result of `extractall`, if it is, the extraction is skipped. For example, if A.zip is unzipped
            to folder structure `A/*.png`, this flag should be True; if B.zip is unzipped to `*.png`, this flag should
            be False.

    Raises:
        RuntimeError: When the hash validation of the ``filepath`` compressed file fails.
        NotImplementedError: When the ``filepath`` file extension is not one of [zip", "tar.gz", "tar"].

    rZ   r   NzNon-empty folder exists in z, skipped extracting.z+ check of compressed file failed: filepath=ry   rz   zWriting into directory: ziptarztar.gzzMUnsupported file type, available options are: ["zip", "tar.gz", "tar"]. name=z type=)r   r=   splitr   nextiterdirr0   rn   r   r   ro   stripr<   endswithzipfileZipFiler   closetarfilerq   NotImplementedError)
rA   r   rv   rd   r   r   	cache_dirZ
_file_typezip_fileZtar_filer3   r3   r4   r      s4    

&

)	r@   rA   r   rv   rd   r   r   rB   r!   c           
   	   C  sP   t  >}|pt|t|  }	t| |	|||d t|	|||d W 5 Q R X dS )ak  
    Download file from URL and extract it to the output directory.

    Args:
        url: source URL link to download file.
        filepath: the file path of the downloaded compressed file.
            use this option to keep the directly downloaded compressed file, to avoid further repeated downloads.
        output_dir: target directory to save extracted files.
            default is the current directory.
        hash_val: expected hash value to validate the downloaded file.
            if None, skip hash validation.
        hash_type: 'md5' or 'sha1', defaults to 'md5'.
        file_type: string of file type for decompressing. Leave it empty to infer the type from url's base file name.
        has_base: whether the extracted files have a base folder. This flag is used when checking if the existing
            folder is a result of `extractall`, if it is, the extraction is skipped. For example, if A.zip is unzipped
            to folder structure `A/*.png`, this flag should be True; if B.zip is unzipped to `*.png`, this flag should
            be False.
        progress: whether to display progress bar.
    )r@   rA   rv   rd   rB   )rA   r   r   r   N)r   r   r   r=   r   r   r   )
r@   rA   r   rv   rd   r   r   rB   r   filenamer3   r3   r4   r   0  s    
)T)Nr   )r6   Nr   T)rZ   Nr   r6   T)r6   rZ   Nr   r6   TT)4
__future__r   hashlibr   r"   r7   r   r+   r   r   r\   r   pathlibr   typingr   r   urllib.errorr   r   r   urllib.parser	   urllib.requestr
   r   monai.config.type_definitionsr   monai.utilsr   r   r   r   r   r   r[   __all__ZDEFAULT_FMTr   r   r   r   r   r   r0   appendr=   rb   r   r   r   r   r3   r3   r3   r4   <module>   sl   
#'    X     =       