
    +j.6                        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 d dl	Z	d dl
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mZmZmZ dd
lmZmZmZ ddl m!Z!m"Z"m#Z#  G d de          Z$ G d de          Z%ddddddde&ej'                 de
j(        e)e
j(                 z  de*de+dz  de+dz  de,de*dz  de)e+         fdZ-ddddde&ej'                 de
j(        de+dz  de+dz  de*dz  de+fdZ.d d!d"d#de&ej'                 d$ej/        d%e+d&e+de+de+fd'Z0ej1        j2        ej3        j4        ddd(de&ej'                 d)ej5        d*ej1        d+ej3        d,e*dz  de+dz  de+fd-Z6d.d/d0d1Z7de&ej'                 d2ej8        d3e+de+fd4Z9	 	 dJde&ej'                 d5ed6e+d7e+dz  de+dz  d8e:dz  de+fd9Z;dd:d;d<ddd=de&ej'                 d>e+d?ee+z  d@e+dz  dAe*dBe:dCe:de+dz  d8e:dz  ddfdDZ<dEe+dFe+dGe*dHe+de+f
dIZ=dS )K    N)BytesIO)urlparse)	BaseModelField)IOInputTypes   )request_logger)is_processing_interruptedsleep_with_interrupt)ApiEndpoint_diagnose_connectivity_display_time_progresssync_op)ApiServerErrorLocalNetworkErrorProcessingInterrupted)audio_ndarray_to_bytesio"audio_tensor_to_contiguous_ndarraytensor_to_bytesioc                   ^    e Zd ZU  edd          Zeed<    edd          Zedz  ed<   dS )UploadRequest.zFilename to uploaddescription	file_nameNzJMime type of the file. For example: image/png, image/jpeg, video/mp4, etc.content_type)__name__
__module____qualname__r   r   str__annotations__r        C/home/wildlama/comfy/ComfyUI/comfy_api_nodes/util/upload_helpers.pyr   r      sg         U3,@AAAIsAAA$u`     L#*     r$   r   c                   X    e Zd ZU  edd          Zeed<    edd          Zeed<   dS )UploadResponse.zURL to GET uploaded filer   download_urlzURL to PUT file to upload
upload_urlN)r   r   r    r   r(   r!   r"   r)   r#   r$   r%   r'   r'   '   sR         c/IJJJL#JJJeC-HIIIJIIIIIr$   r'      	UploadingTi  @ 
max_images	mime_type
wait_labelshow_batch_indextotal_pixelsclsimager-   r.   r/   r0   r1   returnc          	      D  K   g }t          t                    roD ]kt          j                  dk    }|r:|                    fdt          j        d                   D                        V|                               lnit          j                  dk    }|r:|                    fdt          j        d                   D                        n|                               g }	t          t          |          |          }
t          j	                    }t          |
          D ]j}||         }t          |||          }|}|r|r|
dk    r| d|dz    d|
 d	}t          | ||j        |||           d
{V }|	                    |           k|	S )z
    Uploads images to ComfyUI API and returns download URLs.
    To upload multiple images, stack them in the batch dimension first.
       c              3   (   K   | ]}|         V  d S Nr#   ).0iimgs     r%   	<genexpr>z,upload_images_to_comfyapi.<locals>.<genexpr>?   s'      CC!s1vCCCCCCr$   r   c              3   (   K   | ]}|         V  d S r8   r#   )r9   r:   r3   s     r%   r<   z,upload_images_to_comfyapi.<locals>.<genexpr>E   s'      CC58CCCCCCr$   )r1   r.   r
   z (/)N)
isinstancelistlenshapeextendrangeappendmintime	monotonicr   upload_file_to_comfyapiname)r2   r3   r-   r.   r/   r0   r1   tensorsis_batchdownload_urlsnum_to_uploadbatch_start_tsidxtensorimg_ioeffective_labelurlr;   s    `               @r%   upload_images_to_comfyapirV   ,   s      #%G% " 	$ 	$C39~~)H $CCCCuSYq\/B/BCCCCCCCs####	$ u{##a' 	"NNCCCCU5;q>-B-BCCCCCCCNN5!!!  "MGj11M^%%N]## 	" 	""6PYZZZ$ 	J* 	J}q/@/@!+IIsQwIIIIIO+CiQ`bpqqqqqqqqS!!!!r$   )r.   r/   r1   c          	      J   K   t          | |d||d|           d{V d         S )zCUploads a single image to ComfyUI API and returns its download URL.r
   Fr,   Nr   )rV   )r2   r3   r.   r/   r1   s        r%   upload_image_to_comfyapirX   [   s\       (!"%
 
 
 	
 	
 	
 	
 	
 	
 
	 
	r$   mp4aacz	audio/mp4)container_format
codec_namer.   audior[   r\   c                   K   |d         }|d         }t          |          }t          ||||          }t          | |t          j                     d| |           d{V S )z
    Uploads a single audio input to ComfyUI API and returns its download URL.
    Encodes the raw waveform into the specified format before uploading.
    sample_ratewaveform.N)r   r   rJ   uuiduuid4)	r2   r]   r[   r\   r.   r_   r`   audio_data_npaudio_bytes_ios	            r%   upload_audio_to_comfyapirf   q   sz       ]+K":.H6x@@M-m[JZ\fggN(n>b>bP`>b>bdmnnnnnnnnnr$   )	containercodecmax_durationr/   videorg   rh   ri   c                <  K   |z	 |                                 }||k    rt          d|dd| d          nG# t          $ r:}t          j        dt          |                     t          d|           |d}~ww xY wd|j                                         }t          j	                     d	|j                                         }	t                      }
|                    |
||
           |
                    d           t          | |
|	||           d{V S )z
    Uploads a single video to ComfyUI API and returns its download URL.
    Uses the specified container and codec for saving the video before upload.
    NzVideo duration (z.2fz s) exceeds the maximum allowed (zs).z Error getting video duration: %sz-Could not verify video duration from source: zvideo/ra   )formatrh   r   )get_duration
ValueError	Exceptionloggingerrorr!   valuelowerrb   rc   r   save_toseekrJ   )r2   rj   rg   rh   ri   r/   actual_durationeupload_mime_typefilenamevideo_bytes_ios              r%   upload_video_to_comfyapir{      s_      	Y#0022O-- mmmm\hmmm   .  	Y 	Y 	YM<c!ffEEEPQPPQQWXX	Y :	 5 5 7 799*,,::!6!6!8!8::H YYN	MM.%M@@@(nhHXZdeeeeeeeees   18 
A<5A77A<zmodel/gltf-binaryz	model/objapplication/octet-stream)glbobjfbxmodel_3dfile_formatc           	         K   t          | |                                t          j                     d| t                              |d                     d{V S )zDUploads a 3D model file to ComfyUI API and returns its download URL.ra   r|   N)rJ   get_datarb   rc   _3D_MIME_TYPESget)r2   r   r   s      r%   upload_3d_model_to_comfyapir      su       ):<<''+'';(BCC	        r$   file_bytes_iory   rx   progress_origin_tsc                    K   |t          |          }nt          ||          }t          | t          dd          |t          dd           d{V }t	          | |j        ||||	           d{V  |j        S )
zBUploads a single file to ComfyUI API and returns its download URL.N)r   )r   r   z/customers/storagePOST)pathmethodF)endpointdataresponse_modelfinal_label_on_successmonitor_progress)r   r/   r   )r   r   r   r'   upload_filer)   r(   )r2   r   ry   rx   r/   r   request_objectcreate_resps           r%   rJ   rJ      s       &:::&HXYYY"6vFFF%#        K %-          ##r$   r6         ?g       @)r   max_retriesretry_delayretry_backoffr/   r   r)   filer   r   r   r   c                6   K   t          |t                    r[t          j        t                    5  |                    d           ddd           n# 1 swxY w Y   |                                }	nat          |t                    r=t          |d          5 }
|
                                }	ddd           n# 1 swxY w Y   nt          d          i }t                      }|r||d<   n|                    d           d}|}||nt          j                    t          j                    j        dd         }	 |dz  }t#          d	|||          }t%          j        d
          }t)          j                     fd}t)          j         |                      }d}	 t/          j        |d	||pdddt3          |	           d           t%          j        |          }|                    ||	||          }t)          j        |          }t)          j        ||ht(          j                   d{V \  }}||v r'||v r#|                                 t?          d          	 | d{V }n## t(          j         $ r t?          d          dw xY w|4 d{V  |j!        dk    rt          j        t                    5  	 |"                                 d{V }n*# t          $ r |#                                 d{V }Y nw xY wd|j!         }t/          j        |d	||j!        tI          |j%                  ||           ddd           n# 1 swxY w Y   |j!        dv r||k    rtM          | drtN          nd           d{V  ||z  }	 ddd          d{V  
                                 |rM|                                 t          j        t                    5  | d{V  ddd           n# 1 swxY w Y   |rKt          j        t                    5  |(                                 d{V  ddd           n# 1 swxY w Y   t	          d|j!         d          t/          j        |d	||j!        tI          |j%                  d           	 ddd          d{V  
                                 |rM|                                 t          j        t                    5  | d{V  ddd           n# 1 swxY w Y   |rNt          j        t                    5  |(                                 d{V  ddd           dS # 1 swxY w Y   dS dS # 1 d{V swxY w Y   n# t(          j         $ r t?          d          dt$          j)        tT          f$ ry}||k    r1t/          j        |d	||pddt3          |	           dtW          |          j,         dt          |           d           tM          | drtN          nd           d{V  ||z  }Y d}~
                                 |rM|                                 t          j        t                    5  | d{V  ddd           n# 1 swxY w Y   |rKt          j        t                    5  |(                                 d{V  ddd           n# 1 swxY w Y   t[                       d{V }|d          st]          d!          |t_          d"          |d}~ww xY w	 
                                 |rM|                                 t          j        t                    5  | d{V  ddd           n# 1 swxY w Y   |rKt          j        t                    5  |(                                 d{V  ddd           n# 1 swxY w Y   n# 
                                 |rM|                                 t          j        t                    5  | d{V  ddd           n# 1 swxY w Y   |rLt          j        t                    5  |(                                 d{V  ddd           w # 1 swxY w Y   w w xY wZ)#z
    Upload a file to a signed URL (e.g., S3 pre-signed PUT) with retries, Comfy progress display, and interruption.

    Raises:
        ProcessingInterrupted, LocalNetworkError, ApiServerError, Exception
    r   Nrbz2file must be a BytesIO or a filesystem path stringzContent-Typer*   Tr
   PUT)totalc                  L  K   	                                  sut                      rd S r3t           t          t	          j                    z
            d            t          j        d           d {V                                   sd S d S # t          j        $ r Y d S w xY w)Nr   )	is_setr   r   intrH   rI   asynciosleepCancelledError)r2   start_tsstop_evtr/   s   r%   _monitorzupload_file.<locals>._monitor	  s      "//++ -022 ! h.sJDNDTDTW_D_@`@`bfggg!-,,,,,,,,, #//++ - - - - - )   s   "B A#B B#"B#z[File data z bytes])operation_idrequest_methodrequest_urlrequest_headersrequest_paramsrequest_data)timeout)r   headersskip_auto_headers)return_whenzUpload cancelledi  zUpload failed with status )r   r   r   response_status_coderesponse_headersresponse_contenterror_message>               )display_callbackzFailed to upload (HTTP z).zFile uploaded successfully.)r   r   r   r   r   r   zTask cancelledz: z (will retry))r   r   r   r   r   r   internet_accessiblezVUnable to connect to the network. Please check your internet connection and try again.z1The API service appears unreachable at this time.)0r@   r   
contextlibsuppressro   ru   readr!   openrn   setaddrH   rI   rb   rc   hex_generate_operation_idaiohttpClientTimeoutr   Eventcreate_taskr   log_request_responserB   ClientSessionputwaitFIRST_COMPLETEDcancelr   r   statusjsontextdictr   r   r   closeClientErrorOSErrortyper   r   r   r   ) r2   r)   r   r   r   r   r   r/   r   r   fr   r   attemptdelayop_uuidr   r   r   monitor_tasksessreqreq_taskdonependingrespbodymsgrw   diagr   r   s    `      `                      @@r%   r   r      s     $ $   O ++ 	 	IIaLLL	 	 	 	 	 	 	 	 	 	 	 	 	 	 	yy{{	D#		 O$ 	6688D	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 MNNN G"%%% .".n---GE%7%C!!IYIYHjllrr"Gw'1-eZ'RR'd333=??		 		 		 		 		 		 		 		 *88::66-1d	'/)$& '4#=3t99===    (999D((:D'Uf(ggC*3//H"),,/GU\Ul"m"m"mmmmmmmMD't##G(;(;!!!+,>???J%~~~~~~) J J J+,>??TIJ  % % % % % % % %;#%%#,Y77  5)-#4#4#4#4#4#4DD( 5 5 5)-#4#4#4#4#4#4DDD5H4;HH&;)5+0(215-1$,-?-?-1*-                  {&DDDT_I_I_2!&$ GQ-[-C-CW[          . 7% % % % % % % % % % % %H LLNNN '##%%%(33 ' '&&&&&&&&' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '(33 ' '**,,&&&&&&&' ' ' ' ' ' ' ' ' ' ' ' ' ' '] $$Mdk$M$M$MNNN3!-#( *)-%)$,%7%7%B    K% % % % % % % % % % % %H LLNNN '##%%%(33 ' '&&&&&&&&' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '(33 ' '**,,&&&&&&&' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '' 'S% % % % % % % % % % % % % % %L % 	D 	D 	D'(899tC#W- 	] 	] 	]+%%3!-#( *$+Ot!As4yy!A!A!A%)!WW%5"N"NQ"N"N"N    +?I%S%;%;t          & LLNNN '##%%%(33 ' '&&&&&&&&' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '(33 ' '**,,&&&&&&&' ' ' ' ' ' ' ' ' ' ' ' ' ' ' 011111111D-. 'l  !!TUU[\\5	]Q%H LLNNN '##%%%(33 ' '&&&&&&&&' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '(33 ' '**,,&&&&&&&' ' ' ' ' ' ' ' ' ' ' ' ' ' ' LLNNN '##%%%(33 ' '&&&&&&&&' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '(33 ' '**,,&&&&&&&' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ''kw's  AAAB==CC'CV  -I6 5V  6 JV  !&U-M	K$#M$$LM
L?M
U-M	U-M	<U-V  .	PP
P)QQQA
U-'V  ;	TTT6UU"%U"-
U77V  :U7;V  >_#  5\.5B\)7_# >	ZZZ9[  [$'[$-<\))\.._# 5	^

^^0___#Ab'	`<0b<a  ba b"b	=b	bbbbr   rU   r   r   c                    	 t          |          }|j                            dd          d         p|j        pd                    d                              dd          }n# t          $ r d}Y nw xY w|  d| d| d| S )Nr>   r
   upload__try)r   r   rsplitnetlocstripreplacero   )r   rU   r   r   parsedslugs         r%   r   r   }  s    #""3**2.K&-K8RRSVWW__`cehii   44t44g447444s   A A# #A21A2)r+   N)>r   r   rp   rH   rb   ior   urllib.parser   r   torchpydanticr   r   comfy_api.latestr   r   r	    r   _helpersr   r   clientr   r   r   r   common_exceptionsr   r   r   conversionsr   r   r   r   r'   r   	ComfyNodeTensorrA   r   r!   boolrV   rX   Audiorf   VideoContainerMP4
VideoCodecH264Videor{   r   File3Dr   floatrJ   r   r   r#   r$   r%   <module>r     s                 ! ! ! ! ! !   % % % % % % % % - - - - - - - - - -       E E E E E E E E            X W W W W W W W W W             I   J J J J JY J J J  (!*, , ,	bl	,<$u|,,, 	,
 Tz, d
, , *, 
#Y, , , ,f !(*	 	 		bl		<	 Tz		
 d
	 *	 		 	 	 	4 " o o o	bl	o;o 	o
 o o 	o o o o. ',&:&>#.3#( f  f  f	bl	 f; f #	 f
  f * f d
 f 	 f  f  f  fH % 	bl	l  		   & )'+$ $	bl	$$ $ Dj	$
 d
$ $ 	$ $ $ $J  $!'+^' ^' ^'	bl	^'^' C-^'
 *^' ^' ^' ^' d
^' ^' 
^' ^' ^' ^'B53 5S 53 5 5QT 5 5 5 5 5 5r$   