o
    i7                     @   s  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 deZ$G dd deZ%ddddddde&ej' de
j(e)e
j( B de*de+dB de+dB de,de*dB de)e+ fddZ-ddddde&ej' de
j(de+dB de+dB de*dB de+fd d!Z.d"d#d$d%de&ej' d&ej/d'e+d(e+de+de+fd)d*Z0ej1j2ej3j4ddd+de&ej' d,ej5d-ej1d.ej3d/e*dB de+dB de+fd0d1Z6d2d3d4d5Z7de&ej' d6ej8d7e+de+fd8d9Z9		dRde&ej' d:ed;e+d<e+dB de+dB d=e:dB de+fd>d?Z;dd@dAdBdddCde&ej' dDe+dEee+B dFe+dB dGe*dHe:dIe:de+dB d=e:dB ddfdJdKZ<dLe+dMe+dNe*dOe+de+f
dPdQZ=dS )S    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                   @   s:   e Zd ZU edddZeed< edddZedB 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    r!   r!   A/mnt/c/Users/fbmor/ComfyUI/comfy_api_nodes/util/upload_helpers.pyr      s   
 r   c                   @   s6   e Zd ZU edddZeed< ed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#   '   s   
 r#      	UploadingTi  @ 
max_images	mime_type
wait_labelshow_batch_indextotal_pixelsclsimager)   r*   r+   r,   r-   returnc                   s0  g }t  tr. D ]"tjdk}|r'|fddtjd D  q
| q
n t jdk}|rI| fddt jd D  n|  g }	tt||}
t	 }t|
D ]6}|| }t
|||d}|}|r|r|
dkr| d|d  d	|
 d
}t| ||j|||I dH }|	| q_|	S )z
    Uploads images to ComfyUI API and returns download URLs.
    To upload multiple images, stack them in the batch dimension first.
       c                 3       | ]} | V  qd S Nr!   .0i)imgr!   r"   	<genexpr>?       z,upload_images_to_comfyapi.<locals>.<genexpr>r   c                 3   r2   r3   r!   r4   )r/   r!   r"   r8   E   r9   )r-   r*   r	   z (/)N)
isinstancelistlenshapeextendrangeappendmintime	monotonicr   upload_file_to_comfyapiname)r.   r/   r)   r*   r+   r,   r-   tensorsis_batchdownload_urlsnum_to_uploadbatch_start_tsidxtensorimg_ioeffective_labelurlr!   )r/   r7   r"   upload_images_to_comfyapi,   s2   
$$
rR   )r*   r+   r-   c             	      s"   t | |d||d|dI dH d S )zCUploads a single image to ComfyUI API and returns its download URL.r	   Fr(   Nr   )rR   )r.   r/   r*   r+   r-   r!   r!   r"   upload_image_to_comfyapi[   s   

	rS   mp4aacz	audio/mp4)container_format
codec_namer*   audiorV   rW   c          	         sJ   |d }|d }t |}t||||}t| |t  d| |I dH 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   rF   uuiduuid4)	r.   rX   rV   rW   r*   rY   rZ   audio_data_npaudio_bytes_ior!   r!   r"   upload_audio_to_comfyapiq   s   "r`   )	containercodecmax_durationr+   videora   rb   rc   c             
      s   |dur8z|  }||krtd|dd| dW n ty7 } ztdt| td| |d}~ww d|j  }t	  d	|j  }	t
 }
|j|
||d
 |
d t| |
|	||I dH 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/r[   )formatrb   r   )get_duration
ValueError	Exceptionloggingerrorr   valuelowerr\   r]   r   save_toseekrF   )r.   rd   ra   rb   rc   r+   actual_durationeupload_mime_typefilenamevideo_bytes_ior!   r!   r"   upload_video_to_comfyapi   s(   
rt   zmodel/gltf-binaryz	model/objapplication/octet-stream)glbobjfbxmodel_3dfile_formatc                    s0   t | | t  d| t|dI dH S )zDUploads a 3D model file to ComfyUI API and returns its download URL.r[   ru   N)rF   get_datar\   r]   _3D_MIME_TYPESget)r.   ry   rz   r!   r!   r"   upload_3d_model_to_comfyapi   s   

r~   file_bytes_iorr   rq   progress_origin_tsc                    sf   |du rt |d}nt ||d}t| tddd|tdddI dH }t| |j||||d	I dH  |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$   )r.   r   rr   rq   r+   r   request_objectcreate_respr!   r!   r"   rF      s*   	
rF   r1         ?g       @)r   max_retriesretry_delayretry_backoffr+   r   r%   filer   r   r   r   c                   s
  t |tr%tt |d W d   n1 sw   Y  | }	n#t |trDt|d}
|
 }	W d   n1 s>w   Y  nt	di }t
 }|rT||d< n|d d}|}|durc|nt t jdd }	 |d7 }td	|||}tjdd
}t  fdd}t| }d}zztj|d	||pdddt|	 dd tj|d}|j||	||d}t|}tj||htjdI dH \}}||v r||v r|  tdz|I dH }W n tj y   tddw |4 I dH 1 |j!dkrtt9 z	|" I dH }W n ty$   |# I dH }Y nw d|j! }tj|d	||j!t$|j%||d W d   n	1 sFw   Y  |j!dv r||krt&| drat'nddI dH  ||9 }	 W d  I dH  W W 
  |r|  tt |I dH  W d   n	1 sw   Y  |rtt |( I dH  W d   n	1 sw   Y  qptd|j! dtj|d	||j!t$|j%dd 	 W d  I dH  W W 
  |r	|  tt |I dH  W d   n	1 sw   Y  |r,tt |( I dH  W d   dS 1 s%w   Y  dS dS 1 I dH s5w   Y  W n tj yI   tdd tj)t*fy } z||krtj|d	||pbddt|	 dt+|j, dt| dd  t&| drt'nddI dH  ||9 }W Y d}~W 
  |r|  tt |I dH  W d   n	1 sw   Y  |rtt |( I dH  W d   n	1 sw   Y  qpt- I dH }|d! st.d"|t/d#|d}~ww W 
  |r|  tt |I dH  W d   n	1 sw   Y  |r<tt |( I dH  W d   n	1 s7w   Y  nG
  |rc|  tt |I dH  W d   n	1 s^w   Y  |rtt |( I dH  W d   w 1 s~w   Y  w qq)$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                      sp   z+  s*t rW d S rt tt  d  tdI d H    rW d S W d S  tjy7   Y d S w )Nr   )	is_setr   r   intrD   rE   asynciosleepCancelledErrorr!   r.   start_tsstop_evtr+   r!   r"   _monitor	  s   zupload_file.<locals>._monitorz[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suppressrh   rn   readr   openrg   setaddrD   rE   r\   r]   hex_generate_operation_idaiohttpClientTimeoutr   Eventcreate_taskr
   log_request_responser>   ClientSessionputwaitFIRST_COMPLETEDcancelr   r   statusjsontextdictr   r   r   closeClientErrorOSErrortyper   r   r   r   )r.   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msgrp   diagr!   r   r"   r      sj  





	

DD$&

	

D r   r   rQ   r   r   c                 C   sh   zt |}|jddd p|jpdddd}W n ty&   d}Y nw |  d| d| d| S )Nr:   r	   upload__try)r   r   rsplitnetlocstripreplacerh   )r   rQ   r   r   parsedslugr!   r!   r"   r   }  s   .r   )r'   N)>r   r   ri   rD   r\   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Tensorr=   r   r   boolrR   rS   Audior`   VideoContainerMP4
VideoCodecH264Videort   r|   File3Dr~   floatrF   r   r   r!   r!   r!   r"   <module>   s,   		
3


$

%	

 ""