o
    iJ                     @   s  d dl Z d dlmZ d dlZd dlmZ d dlmZmZm	Z	 d dl
mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZ d dlmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$ ddd	d
Z%G dd dej&Z'G dd dej&Z(G dd deZ)de)fddZ*dS )    N)BytesIO)override)IOComfyExtensionInput)CreateVideoRequestCreateVideoRequestSourceCreateVideoResponseImageAsyncTaskResponseImageDownloadResponseImageEnhanceRequestImageStatusResponseOutputInformationVideo
ResolutionVideoAcceptResponseVideoCompleteUploadRequestVideoCompleteUploadRequestPartVideoCompleteUploadResponseVideoEnhancementFilterVideoFrameInterpolationFilterVideoStatusResponse)	ApiEndpointdownload_url_to_image_tensordownload_url_to_video_outputget_fs_object_sizeget_number_of_imagespoll_opsync_opupload_images_to_comfyapi validate_container_format_is_mp4zslf-1slc-1zslp-2.5)zStarlight (Astra) FastzStarlight (Astra) CreativezStarlight Precise 2.5c                   @   sz   e Zd Zedd Ze											
		ddedejdededede	de	dede
de
de
dededejfddZdS )TopazImageEnhancec                 C   sd  t jddddt jjddgdt jdt jjd	d
ddd
dt jjdg dd
d
dt jjdd
d
dd
dt jjdddddt jj	d
dd
d	t jjdddddt jj	d
dd
d	t jjddd
dd
dt j
jdd d d!d"t jj	d
d#d
d	t j
jd$d d d!d"t jj	d
d%d
d	t j
jd&d'd"d(d"t jjd
d)t jjd*d
d
d+d
dt jjd,d
d
d-d
dgt j gt jjt jjt jjgd
d.S )/Nr!   zTopaz Image Enhancezapi node/image/Topazz2Industry-standard upscaling and image enhancement.model	ReimagineoptionsimagepromptT z5Optional text prompt for creative upscaling guidance.)	multilinedefaulttooltipoptionalsubject_detection)All
Foreground
Background)r%   r,   advancedface_enhancementz-Enhance faces (if present) during processing.)r*   r,   r+   r1   face_enhancement_creativityg              ?{Gz?z.Set the creativity level for face enhancement.)r*   minmaxstepdisplay_moder,   r+   r1   face_enhancement_strengthzAControls how sharp enhanced faces are relative to the background.crop_to_fillFzBy default, the image is letterboxed when the output aspect ratio differs. Enable to crop the image to fill the output dimensions.output_widthr   i }     zmZero value means to calculate automatically (usually it will be original size or output_height if specified).output_heightzJZero value means to output in the same height as original or output width.
creativity   	   )r*   r6   r7   r8   r9   r,   face_preservationz#Preserve subjects' facial identity.color_preservationzPreserve the original colors.node_iddisplay_namecategorydescriptioninputsoutputshiddenis_api_node)r   SchemaCombor   ImageStringBooleanFloatNumberDisplaynumberIntsliderOutputHiddenauth_token_comfy_orgapi_key_comfy_org	unique_idcls r^   9/mnt/c/Users/fbmor/ComfyUI/comfy_api_nodes/nodes_topaz.pydefine_schema.   s   
	dzTopazImageEnhance.define_schemar(   r.   Tr4   皙?Fr   r@   r"   r&   r'   r-   r2   r3   r:   r;   r<   r>   r?   rB   rC   returnc                    s  t |dkrtdt| |ddddI d H }t| tdddtt||||||||	r+|	nd |
r0|
nd |t| t| |d	 d
dddI d H }t	| td|j
 dtdd dd dd dddI d H  t| td|j
 dtddI d H }tt|jI d H S )Nr=   z"Only one input image is supported.z	image/pngi   )
max_images	mime_typetotal_pixelsz'/proxy/topaz/image/v1/enhance-gen/asyncPOSTpathmethodr   png)r"   r'   r-   r2   r3   r:   r;   r<   r>   r?   rB   rC   
source_urloutput_formatzmultipart/form-data)response_modeldatacontent_typez/proxy/topaz/image/v1/status/rh   c                 S      | j S Nstatusxr^   r^   r_   <lambda>       z+TopazImageEnhance.execute.<locals>.<lambda>c                 S      t | ddS Nprogressr   getattrru   r^   r^   r_   rw          c                 S   s
   | j d S )N{Gz?)creditsru   r^   r^   r_   rw      s   
 g       @<   )poll_endpointrm   status_extractorprogress_extractorprice_extractorpoll_intervalestimated_durationz/proxy/topaz/image/v1/download/F)rm   monitor_progress)r   
ValueErrorr   r   r   r
   r   strlowerr   
process_idr   r   r   
NodeOutputr   download_url)r]   r"   r&   r'   r-   r2   r3   r:   r;   r<   r>   r?   rB   rC   r   initial_responseresultsr^   r^   r_   execute   sZ   





zTopazImageEnhance.executeN)r(   r.   Tr4   ra   Fr   r   r@   TT)__name__
__module____qualname__classmethodr`   r   r   rO   boolfloatintr   r   r   r^   r^   r^   r_   r!   -   sX    
t	
r!   c                   @   sp   e Zd Zedd Ze									dd
ejdedededededede	de	dede
dedejfddZdS )TopazVideoEnhancec                 C   s<  t jddddt jdt jjdddt jjd	tt d
t jjdddgd
t jjdg ddddddt jjddddt jjddgddddt j	jddddt j
jddddt j	jddd d!t j
jd"dd#t jjd$dd%ddd&t jjd'd(d)d*d)t j
jd+ddd,	t jjd-g d.d/d0dddgt j gt jjt jjt jjgdd1S )2Nr   zTopaz Video Enhancezapi node/video/TopazzLBreathe new life into video with powerful upscaling and recovery technology.videoupscaler_enabledT)r*   upscaler_modelr$   upscaler_resolutionzFullHD (1080p)z
4K (2160p)upscaler_creativity)lowmiddlehighr   z>Creativity level (applies only to Starlight (Astra) Creative).)r%   r*   r+   r,   r1   interpolation_enabledF)r*   r,   interpolation_modelapo-8)r%   r*   r,   r1   interpolation_slowmor=      zvSlow-motion factor applied to the input video. For example, 2 makes the output twice as slow and doubles the duration.)r*   r6   r7   r9   r+   r,   r1   interpolation_frame_rater         zOutput frame rate.)r*   r6   r7   r9   r+   r,   interpolation_duplicatez7Analyze the input for duplicate frames and remove them.)r*   r+   r,   r1   !interpolation_duplicate_thresholdr5   gMbP?g?z+Detection sensitivity for duplicate frames.)r*   r6   r7   r8   r9   r+   r,   r1   dynamic_compression_level)LowMidHighr   z
CQP level.rD   )r   rM   Videor   rQ   rN   listUPSCALER_MODELS_MAPkeysrU   rS   rT   rR   rW   rX   rY   rZ   r[   r\   r^   r^   r_   r`      s   
	?zTopazVideoEnhance.define_schemar   Fr   r=   r   r5   r   r   r   r   r   r   r   r   r   r   r   r   r   rb   c                     s  |du r|du rt dt| | \}}t| }| }| }|}|}|}g }|rd|v r8d}d}nd}d}|| }||krY|}t|| }||krX|}t|| }n|}t|| }||krm|}t|| }|d d	krw|d
7 }|d d	kr|d
7 }|tt	| t	| dkr|nd t	| dkrdnd d |r|	}|t
|||	|
|d t| tdddtttdt|t|| |t||dd|tt||d|dd|dddddI d H }t| td|j dddtddd I d H }t|jd
krtd!tjd"d#id$4 I d H }t|trE|d	 |j|jd	 |dd%4 I d H }|jd& }W d   I d H  n1 I d H s?w   Y  nBt !|d'3}|j|jd	 |dd%4 I d H }|jd& }W d   I d H  n1 I d H srw   Y  W d    n	1 sw   Y  W d   I d H  n1 I d H sw   Y  t| td|j d(ddt"t#t$d
|d)gd*d+d,dI d H  t%| td|j d-d.t&d/d0 d1d0 d2d0 d3d4d5I d H }t'(t)|j*j+I d H S )6NFzFThere is nothing to do: both upscaling and interpolation are disabled.1080pi8  i  ip  i      r   r=   r    T)r"   r?   isOptimizedMode)r"   slowmofps	duplicateduplicate_thresholdz/proxy/topaz/video/rf   rg   mp4)widthheight)	containersizeduration
frameCount	frameRate
resolutionAACCopy)r   r   
audioCodecaudioTransferdynamicCompressionLevel)sourcefiltersoutputzCreating taskzTask created)rm   rn   
wait_labelfinal_label_on_successz/acceptPATCHzPreparing uploadzUpload started)rm   r   r   zXLarge files are not currently supported. Please open an issue in the ComfyUI repository.zContent-Typez	video/mp4)headers)rn   raise_for_statusEtagrbz/complete-upload)partNumeTag)uploadResultszFinalizing uploadzUpload completedz/statusrp   c                 S   rq   rr   rs   ru   r^   r^   r_   rw     rx   z+TopazVideoEnhance.execute.<locals>.<lambda>c                 S   ry   rz   r|   ru   r^   r^   r_   rw     r~   c                 S   s&   | j r| j jd r| j jd d S d S )Nr   r   )	estimatescostru   r^   r^   r_   rw     s   & g      $@i@  )rm   r   r   r   r   max_poll_attempts),r   r   get_dimensionsr   get_frame_rateget_durationget_stream_sourceappendr   r   r   r   r   r	   r   r   r   get_frame_countr   r   	requestIdr   lenurlsNotImplementedErroraiohttpClientSession
isinstancer   seekputr   builtinsopenr   r   r   r   r   r   r   r   downloadurl) r]   r   r   r   r   r   r   r   r   r   r   r   r   	src_width
src_heightsrc_frame_rateduration_secsrc_video_streamtarget_widthtarget_heighttarget_frame_rater   target_pixel_pmax_long_sidearinitial_res
upload_ressessionresupload_etag
video_filefinal_responser^   r^   r_   r   5  s  	




 * * *	
zTopazVideoEnhance.executeN)r   Fr   r=   r   Fr5   r   )r   r   r   r   r`   r   r   r   r   r   r   r   r   r   r^   r^   r^   r_   r      sN    
O	
r   c                   @   s(   e Zd Zedeeej  fddZdS )TopazExtensionrb   c                    s
   t tgS rr   )r!   r   )selfr^   r^   r_   get_node_list  s   zTopazExtension.get_node_listN)	r   r   r   r   r   typer   	ComfyNoder   r^   r^   r^   r_   r     s    r   rb   c                      s   t  S rr   )r   r^   r^   r^   r_   comfy_entrypoint  s   r  )+r   ior   r   typing_extensionsr   comfy_api.latestr   r   r   comfy_api_nodes.apis.topazr   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   comfy_api_nodes.utilr   r   r   r   r   r   r   r   r   r   r  r!   r   r   r  r^   r^   r^   r_   <module>   s"    H, 8 j	