o
    it,                     @   s(  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	m
Z
m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mZ d dlmZ d	d
lmZ d	dlmZmZmZmZmZ d	dlm Z  d	dl!m"Z"m#Z#m$Z$ d	dl%m&Z& h dZ'ddddddde(deee) B e(B eB dB de*dB de+de*de*de,ej- ddfddZ.dddde(de*de,ej- dej/fdd Z0dddd!d"e(de*de+de,ej- dej1f
d#d$Z2dddde(de*de,ej- defd%d&Z3d'e(de(d(e+de(fd)d*Z4ddddd+de(d,e(d-e(dB de*dB de+de,ej- dej5fd.d/Z6dS )0    N)BytesIO)Path)IO)urljoinurlparse)ClientErrorContentTypeError)	InputImplTypes)get_output_directory   )request_logger)default_base_urlget_auth_headeris_processing_interruptedsleep_with_interruptto_aiohttp_url)_diagnose_connectivity)ApiServerErrorLocalNetworkErrorProcessingInterrupted)bytesio_to_image_tensor>                        ?g       @)timeoutmax_retriesretry_delayretry_backoffclsurldestr    r!   r"   r#   r$   returnc                   s:  t |ttfst|dstdd}|}i }	t| }
|
js;|
js;|du r)tdtt	 
dd | d} t|}		 |d7 }td	| |}tj|d
}t |ttf}d}d}d d}d}zztt tj|d	| d W d   n1 syw   Y  tj|d}t   fdd}t| }t|jt| |	d}tj||htjdI dH \}}||v r||v r|  tt |I dH  W d   td1 sw   Y  tdz|I dH }W n tjy   tddw |4 I dH z |j dkrttJ z	|! I dH }W n$ t"tfy2   |# I dH }t$|dkr(|ndt$| d}Y nw tj|d	| |j t%|j&|d|j  d W d   n	1 sRw   Y  |j t'v r||krt(||dddI dH  ||9 }	 W d  I dH  W W  dur )  |r|  tt |I dH  W d   n	1 sw   Y  |r|* s|  tt |I dH  W d   n	1 sw   Y  |rtt |+ I dH  W d   n	1 sw   Y  |rtt |,  |+  W d   n	1 sw   Y  q;td|j  d|rItt|}tt |j-j.ddd W d   n	1 s<w   Y  t/|d}|}n|}d}	 ztj0|j12dddI dH }W n tj3yk   d}Y n tjyx   tddw t4 rtd|s|j15 rnqM|6| |t$|7 }qNt |t7rtt |8d W d   n	1 sw   Y  tj|d	| |j t%|j&d| d d! 	 W d  I dH  W W  dur )  |r|  tt |I dH  W d   n	1 s w   Y  |r,|* s,|  tt |I dH  W d   n	1 s'w   Y  |rLtt |+ I dH  W d   n	1 sGw   Y  |rptt |,  |+  W d   dS 1 siw   Y  dS dS 1 I dH syw   Y  W n tjy   tdd t9t:fyr } z||krYtj|d	| t;|j< d"t| d#d$ t(||dddI dH  ||9 }W Y d}~W  durΈ )  |r|  tt |I dH  W d   n	1 sw   Y  |r|* s|  tt |I dH  W d   n	1 sw   Y  |r7tt |+ I dH  W d   n	1 s2w   Y  |rXtt |,  |+  W d   n	1 sSw   Y  q;t= I dH }|d% sit>d&|t?d'|d}~ww W  dur} )  |r|  tt |I dH  W d   n	1 sw   Y  |r|* s|  tt |I dH  W d   n	1 sw   Y  |rtt |+ I dH  W d   n	1 sw   Y  |rtt |,  |+  W d   n	1 sw   Y  n dur )  |r3|  tt |I dH  W d   n	1 s.w   Y  |rZ|* sZ|  tt |I dH  W d   n	1 sUw   Y  |rztt |+ I dH  W d   n	1 suw   Y  |rtt |,  |+  W d   w 1 sw   Y  w q<)(a  Stream-download a URL to `dest`.

    `dest` must be one of:
      - a BytesIO (rewound to 0 after write),
      - a file-like object opened in binary write mode (must implement .write()),
      - a filesystem path (str | pathlib.Path), which will be opened with 'wb'.

    If `url` starts with `/proxy/`, `cls` must be provided so the URL can be expanded
    to an absolute URL and authentication headers can be applied.

    Raises:
        ProcessingInterrupted, LocalNetworkError, ApiServerError, Exception (HTTP and other errors)
    writezNdest must be a path (str|Path) or a binary-writable object providing .write().r   Nz<For relative 'cloud' paths, the `cls` parameter is required./Tr   GET)total)operation_idrequest_methodrequest_url)r    c                      sR   z   st rW d S tdI d H     rW d S W d S  tjy(   Y d S w )Nr   )is_setr   asynciosleepCancelledError stop_evtr3   C/mnt/c/Users/fbmor/ComfyUI/comfy_api_nodes/util/download_helpers.py_monitorX   s   z)download_url_to_bytesio.<locals>._monitor)headers)return_whenzTask cancelledi  i   z[text z bytes]zHTTP )r,   r-   r.   response_status_coderesponse_headersresponse_contenterror_messagezFailed to download (HTTP z).)parentsexist_okwbi   r       z
[streamed z bytes to dest])r,   r-   r.   r:   r;   r<   z: z (will retry))r,   r-   r.   r=   internet_accessiblezVUnable to connect to the network. Please check your internet connection and try again.z4The remote service appears unreachable at this time.)@
isinstancestrr   hasattr
ValueErrorr   schemenetlocr   r   rstriplstripr   _generate_operation_idaiohttpClientTimeout
contextlibsuppress	Exceptionr   log_request_responseClientSessionr0   Eventcreate_taskgetr   waitFIRST_COMPLETEDcancelr   r2   statusjsonr   textlendictr8   _RETRY_STATUSr   setdonecloseflushparentmkdiropenwait_forcontentreadTimeoutErrorr   at_eofr(   r   seekr   OSErrortype__name__r   r   r   )r%   r&   r    r!   r"   r#   r$   attemptdelayr8   
parsed_urlop_idtimeout_cfgis_path_sinkfhandlesessionmonitor_taskreq_taskr7   r`   pendingrespbodyr[   psinkwrittenchunkediagr3   r4   r6   download_url_to_bytesio    s  	

&

W

 



W
$B


	



W


  r   r    r$   c                   s&   t  }t| |||dI dH  t|S )z@Downloads an image from a URL and returns a [B, H, W, C] tensor.r   N)r   r   r   r%   r    r$   resultr3   r3   r6   download_url_to_image_tensor   s   r   r    r!   r$   	video_urlc                   s*   t  }t| ||||dI dH  t|S )z:Downloads a video from a URL and returns a `VIDEO` output.r   N)r   r   r	   VideoFromFile)r   r    r!   r$   r   r3   r3   r6   download_url_to_video_output   s   
r   c                   s"   t  }t| |||dI dH  |S )zFDownloads content from a URL and returns a new BytesIO (rewound to 0).r   N)r   r   r   r3   r3   r6   download_url_as_bytesio   s   r   methodro   c              	   C   sv   zt |}|jddd p|jpdddd}W n ty&   d}Y nw |  d| d| dt j	d d  S )Nr)   r   download__try   )
r   pathrsplitrH   stripreplacerP   uuiduuid4hex)r   r%   ro   parsedslugr3   r3   r6   rK      s   .(rK   )task_idr    r!   r$   file_formatr   c          	         sx   | d }t }t| ||||dI dH  |dur5tt }|| d|  }||  |d t	j
||dS )zDownloads a 3D model file from a URL into memory as BytesIO.

    If task_id is provided, also writes the file to disk in the output directory
    for backward compatibility with the old save-to-disk behavior.
    .r   Nr   )sourcer   )rJ   lowerr   r   r   r   write_bytesgetvaluerk   r
   File3D)	r%   r   r   r    r!   r$   data
output_diroutput_pathr3   r3   r6   download_url_to_file_3d	  s    

r   )7r0   rN   r   ior   pathlibr   typingr   urllib.parser   r   rL   torchaiohttp.client_exceptionsr   r   comfy_api.latestCOMFY_IOr	   r
   folder_pathsr    r   _helpersr   r   r   r   r   clientr   common_exceptionsr   r   r   conversionsr   r^   rD   bytesfloatintrm   	ComfyNoder   Tensorr   r   r   r   rK   r   r   r3   r3   r3   r6   <module>   s    	
 ?


