
    bi>              #       H   d dl Z d dlZd dlmZmZmZmZmZ d dlZddl	m
Z
 ddlmZmZ  e       rJd dlZddlmZ ddlmZ  e       rd dlZej*                  ej,                  ej.                  ej0                  d	Zd d
lmZ dedefdZ	 	 	 	 	 	 	 	 	 	 	 	 d+dedddeed      dedee    dee    ded   ded   ded   deded   ded   dee!   d ee!   fd!Z"	 	 	 	 d,d"ejF                  deed      ded   ded   def
d#Z$	 	 	 	 	 	 	 	 	 d-dddeed      dedee    dee    ded   ded   dedee!   d ee!   fd$Z%	 	 	 	 	 	 	 	 	 	 	 	 d+dedddeed      dedee    dee    ded   ded   ded   deded   ded   dee!   d ee!   deej6                  eej6                     edf   fd%Z&	 	 d.ded&edej6                  f   dee    dee    fd'Z'd"ejF                  fd(Z(	 	 d.d&edej6                  f   dee    dee    fd)Z)	 	 d.ded&edej6                  f   dee    dee    ddf
d*Z*y)/    N)ListLiteralOptionalUnioncast   )	deprecate)is_safetensors_availableis_torch_available   )VaeImageProcessor)VideoProcessor)float16float32bfloat16uint8)Imagedatareturnc                     | j                  d      ry| j                  d      ry| j                  d      s| j                  d      ry| j                  d      ry	y
)Ns   jpegs   PNG

pngs   GIF87as   GIF89agifs   BMbmpunknown)
startswith)r   s    W/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/utils/remote_utils.pydetect_image_typer   .   sM    {#	-	.		#ty'A		    binaryendpointtensorztorch.Tensor	processor)r   r   
do_scalingscaling_factorshift_factoroutput_type)mp4pilptreturn_typeimage_format)r   jpgpartial_postprocessinput_tensor_typeoutput_tensor_typeheightwidthc                     |j                   dk(  r||t        d      |dk(  r(|dk(  r#|	s!t        |t        t        f      st        d      |r|t        dddd	
       y y y )N   z1`height` and `width` required for packed latents.r*   r)   z`processor` is required.r$   1.0.0zQ`do_scaling` is deprecated, pass `scaling_factor` and `shift_factor` if required.Fstandard_warn)ndim
ValueError
isinstancer   r   r	   )r!   r"   r#   r$   r%   r&   r'   r+   r,   r.   r/   r0   r1   r2   s                 r   check_inputs_decoder;   :   sv      {{aFNu}LMMt5 #9'8.&IJ344n,_		
 -zr   responsec                    |dk(  s|dk(  ro|m| j                   }| j                  }t        j                  |d         }|d   }t        |   }	t        j                  t        |      |	      j                  |      }|dk(  r|rS|dk(  rED 
cg c]%  }
t        j                  |
j                               ' }}
t        |      dk(  r|d   }|S |dk(  r}|S ||dk(  r}|S t        |t              r7t        t         t        j                     |j#                  d      d         }|S t        t        j                  |j%                  d      d         }S |dk(  rf|dk(  ra|_t        j&                  t)        j*                  | j                               j-                  d	      }t/        | j                         }||_        |S |dk(  r||dk(  rrj3                  dd
dd      j5                         j                         dz  j7                         j9                  d      D 
cg c]  }
t        j                  |
       }}
|S |dk(  r}S |dk(  r|dk(  r| j                   }S c c}
w c c}
w )Nr*   r)   shapedtyper?   r   r   )r'   RGBr   r4      r   r(   )contentheadersjsonloads	DTYPE_MAPtorch
frombuffer	bytearrayreshaper   	fromarraynumpylenr:   r   r   r   postprocess_videopostprocessopenioBytesIOconvertr   formatpermutefloatroundastype)r<   r#   r'   r+   r.   output_tensor
parametersr>   r?   torch_dtypeimageoutputdetected_formats                r   postprocess_decoder`   \   s    d{e3	8M ((%%


:g./7#&((=)AU]]^cdde#FSTU%//%++-8TTv;!##AYF> M= $&: M7  K4$7&4 M1 i8!U[[)!33Mu3UVWXF. M% "!--m-OPQRF$ M 
	+"69;LBJJx'7'789AA%H+H,<,<=' M 
	)"7% ,33Aq!Q?EEGMMORUU\\^eefmn &F  M	 D "F M 
	+"6!!MC U2s   
*I I%c
                    i }
|||t        | j                        t        | j                        j	                  d      d   d}|r|||d<   |r|||d<   |r|||d<   n|r	||||d<   ||	
||d<   |	|d<   d	|
d
<   d	|
d<   |dk(  r|dk(  r|d|
d<   n|dk(  r|dk(  r|d|
d<   n
|dk(  rd|
d<   t
        j                  j                  | d      }|||
dS )N.)r,   r'   r.   r>   r?   r%   r&   r$   r1   r2   ztensor/binaryzContent-TypeAcceptr)   r-   z
image/jpegr   z	image/pngr(   z
text/plainr"   r   paramsrD   )listr>   strr?   splitsafetensorsrH   _tobytes)r"   r#   r$   r%   r&   r'   r,   r.   r1   r2   rD   r[   tensor_datas                r   prepare_decoderm      s7    G$"2fll#V\\"((-b1J n0'5
#$l.%1
>"n,#-
< 	.<3G#-
< e/%
8#
7-GN'GHe 5):K(		,%"7I<M'		(##,,VX>K:'JJr   c                 N   |
dk(  rt        dddd       d}
|dk(  rt        ddd	d       d}t        | |||||||||	|
|||       t        ||||||||	||

      }t        j                  | fi |}|j
                  st        |j                               t        |||||	      }|S )aM  
    Hugging Face Hybrid Inference that allow running VAE decode remotely.

    Args:
        endpoint (`str`):
            Endpoint for Remote Decode.
        tensor (`torch.Tensor`):
            Tensor to be decoded.
        processor (`VaeImageProcessor` or `VideoProcessor`, *optional*):
            Used with `return_type="pt"`, and `return_type="pil"` for Video models.
        do_scaling (`bool`, default `True`, *optional*):
            **DEPRECATED**. **pass `scaling_factor`/`shift_factor` instead.** **still set
            do_scaling=None/do_scaling=False for no scaling until option is removed** When `True` scaling e.g. `latents
            / self.vae.config.scaling_factor` is applied remotely. If `False`, input must be passed with scaling
            applied.
        scaling_factor (`float`, *optional*):
            Scaling is applied when passed e.g. [`latents /
            self.vae.config.scaling_factor`](https://github.com/huggingface/diffusers/blob/7007febae5cff000d4df9059d9cf35133e8b2ca9/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py#L1083C37-L1083C77).
            - SD v1: 0.18215
            - SD XL: 0.13025
            - Flux: 0.3611
            If `None`, input must be passed with scaling applied.
        shift_factor (`float`, *optional*):
            Shift is applied when passed e.g. `latents + self.vae.config.shift_factor`.
            - Flux: 0.1159
            If `None`, input must be passed with scaling applied.
        output_type (`"mp4"` or `"pil"` or `"pt", default `"pil"):
            **Endpoint** output type. Subject to change. Report feedback on preferred type.

            `"mp4": Supported by video models. Endpoint returns `bytes` of video. `"pil"`: Supported by image and video
            models.
                Image models: Endpoint returns `bytes` of an image in `image_format`. Video models: Endpoint returns
                `torch.Tensor` with partial `postprocessing` applied.
                    Requires `processor` as a flag (any `None` value will work).
            `"pt"`: Support by image and video models. Endpoint returns `torch.Tensor`.
                With `partial_postprocess=True` the tensor is postprocessed `uint8` image tensor.

            Recommendations:
                `"pt"` with `partial_postprocess=True` is the smallest transfer for full quality. `"pt"` with
                `partial_postprocess=False` is the most compatible with third party code. `"pil"` with
                `image_format="jpg"` is the smallest transfer overall.

        return_type (`"mp4"` or `"pil"` or `"pt", default `"pil"):
            **Function** return type.

            `"mp4": Function returns `bytes` of video. `"pil"`: Function returns `PIL.Image.Image`.
                With `output_type="pil" no further processing is applied. With `output_type="pt" a `PIL.Image.Image` is
                created.
                    `partial_postprocess=False` `processor` is required. `partial_postprocess=True` `processor` is
                    **not** required.
            `"pt"`: Function returns `torch.Tensor`.
                `processor` is **not** required. `partial_postprocess=False` tensor is `float16` or `bfloat16`, without
                denormalization. `partial_postprocess=True` tensor is `uint8`, denormalized.

        image_format (`"png"` or `"jpg"`, default `jpg`):
            Used with `output_type="pil"`. Endpoint returns `jpg` or `png`.

        partial_postprocess (`bool`, default `False`):
            Used with `output_type="pt"`. `partial_postprocess=False` tensor is `float16` or `bfloat16`, without
            denormalization. `partial_postprocess=True` tensor is `uint8`, denormalized.

        input_tensor_type (`"binary"`, default `"binary"`):
            Tensor transfer type.

        output_tensor_type (`"binary"`, default `"binary"`):
            Tensor transfer type.

        height (`int`, **optional**):
            Required for `"packed"` latents.

        width (`int`, **optional**):
            Required for `"packed"` latents.

    Returns:
        output (`Image.Image` or `List[Image.Image]` or `bytes` or `torch.Tensor`).
    base64zinput_tensor_type='base64'r5   z9input_tensor_type='base64' is deprecated. Using `binary`.Fr6   r    zoutput_tensor_type='base64'z:output_tensor_type='base64' is deprecated. Using `binary`.)
r"   r#   r$   r%   r&   r'   r,   r.   r1   r2   )r<   r#   r'   r+   r.   )	r	   r;   rm   requestspostokRuntimeErrorrE   r`   )r!   r"   r#   r$   r%   r&   r'   r+   r,   r.   r/   r0   r1   r2   kwargsr<   r^   s                    r   remote_decoderu      s    x H$(G		
 %X%)H		
 &  %!!/F }}X00H;;8==?++/F Mr   r]   c                      y )N )r!   r]   r%   r&   s       r   check_inputs_encoderx   Q  s     	r   c                     | j                   }| j                  }t        j                  |d         }|d   }t        |   }t        j                  t        |      |      j                  |      }|S )Nr>   r?   r@   )	rC   rD   rE   rF   rG   rH   rI   rJ   rK   )r<   rZ   r[   r>   r?   r\   s         r   postprocess_encoderz   Z  sj     $$M!!JJJz'*+EwEE"K$$Y}%=[QYYZ_`Mr   c                    i }i }|||d<   |||d<   t        | t        j                        rqt        j                  j	                  | j                         d      }t        | j                        |d<   t        | j                        j                  d      d   |d<   n7t        j                         }| j                  |d	       |j                         }|||d
S )Nr%   r&   r"   r>   rb   rc   r?   PNG)rU   re   )r:   rH   Tensorrj   rk   
contiguousrg   r>   rh   r?   ri   rR   rS   savegetvalue)r]   r%   r&   rD   r[   r   buffers          r   prepare_encoder   f  s    
 GJ!'5
#$%1
>"%&  ))%*:*:*<hG"5;;/
7!%++.44S9"=
7

6%
( J7CCr   c                     t        | |||       t        |||      }t        j                  | fi |}|j                  st        |j                               t        |      }|S )a%  
    Hugging Face Hybrid Inference that allow running VAE encode remotely.

    Args:
        endpoint (`str`):
            Endpoint for Remote Decode.
        image (`torch.Tensor` or `PIL.Image.Image`):
            Image to be encoded.
        scaling_factor (`float`, *optional*):
            Scaling is applied when passed e.g. [`latents * self.vae.config.scaling_factor`].
            - SD v1: 0.18215
            - SD XL: 0.13025
            - Flux: 0.3611
            If `None`, input must be passed with scaling applied.
        shift_factor (`float`, *optional*):
            Shift is applied when passed e.g. `latents - self.vae.config.shift_factor`.
            - Flux: 0.1159
            If `None`, input must be passed with scaling applied.

    Returns:
        output (`torch.Tensor`).
    )r]   r%   r&   )r<   )rx   r   rp   rq   rr   rs   rE   rz   )r!   r]   r%   r&   rt   r<   r^   s          r   remote_encoder   |  sn    8 	 %!F
 }}X00H;;8==?++F Mr   )NTNNr)   r)   r-   Fr    r    NN)Nr)   r)   F)	NTNNr)   r-   FNN)NN)+rR   rE   typingr   r   r   r   r   rp   deprecation_utilsr	   import_utilsr
   r   rH   image_processorr   video_processorr   safetensors.torchrj   r   r   r   r   rG   PILr   bytesrh   r   boolrW   intr;   Responser`   rm   ru   rx   rz   r   r   rw   r   r   <module>r      s    
  7 7  ( F 30!  ====NN	I 	E 	c 	 IM&*$(/4/4*/ %+3,4 


 CDE
 	

 UO
 5/
 +,
 +,
 ,'
 
 x(
  )
 SM
 C=
H IM/4/4 %22CDE2 +,2 +,	2
 2n IM&*$(/4*/ % (K(KCDE(K (K UO	(K
 5/(K +,(K ,'(K (K SM(K C=(K\ IM&*$(/4/4*/ %+3,4 RRR CDER 	R
 UOR 5/R +,R +,R ,'R R x(R  )R SMR C=R 5;;U[[)5.@ARp '+$(			,-	 UO	 5/				 '+$(D,-DUOD 5/D2 '+$(	--,-- UO- 5/	-
 -r   