
    biE                        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mZm	Z	 d dl
Zd dlZd dlZddlmZmZmZ ddlmZ  ej*                         Z ee      Zed        Zddeej4                  j4                     d	ed
edefdZddefdZddefdZ	 dde	eej@                     eej4                  j4                     f   ded
efdZ!	 	 	 	 	 dde	eej@                     eej4                  j4                     f   ded
ede"dee   dee   defdZ#y)    N)contextmanager)ListOptionalUnion   )BACKENDS_MAPPINGis_imageio_availableis_opencv_available)
get_loggerc              #   ^   K   t        j                  |       }| |j                          y wN)ioBufferedWriterflush)raw_ffs     W/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/utils/export_utils.pybuffered_writerr      s$     
% A
GGGIs   +-imageoutput_gif_pathfpsreturnc                     | t        j                  d      j                  }| d   j                  |d| dd  dd|z  d       |S )	Nz.gifsuffixr   Tr   Fi  )save_allappend_imagesoptimizedurationloop)tempfileNamedTemporaryFilenamesave)r   r   r   s      r   export_to_gifr%      sW    "55VDII	!HMMABi       output_ply_pathc           	         | t        j                  d      j                  }| j                  j	                         j                         j                         }| j                  j                         j                         }t        j                  dD cg c];  }| j                  |   j	                         j                         j                         = c}d      }t        t        |d            5 }|j                  d       |j                  d	       |j                  t        d
t        |       dd             |j                  d       |j                  d       |j                  d       |3|j                  d       |j                  d       |j                  d       |9|j                  t        dt        |       dd             |j                  d       |j                  d       ||dz  j!                         j#                  t$              }t'        |j)                         |j)                               D cg c]  \  }}g || }}}t+        j,                  d      }	|D ]   }
|j                   |	j.                  |
        " nHt+        j,                  d      }	|j)                         D ]   }|j                   |	j.                  |        " |Ut+        j,                  d      }	|j)                         D ]-  }|j                   |	j.                  t        |      g|        / ddd       |S c c}w c c}}w # 1 sw Y   |S xY w)z&
    Write a PLY file for a mesh.
    Nz.plyr   RGBr   axiswbs   ply
s    format binary_little_endian 1.0
zelement vertex 
asciis   property float x
s   property float y
s   property float z
s   property uchar red
s   property uchar green
s   property uchar blue
zelement face s%   property list uchar int vertex_index
s   end_header
go@z<3f3Bz<3fz<B3I)r!   r"   r#   vertsdetachcpunumpyfacesnpstackvertex_channelsr   openwritebyteslenroundastypeintziptoliststructStructpack)meshr'   coordsr3   xrgbr   coordverticesformatitemvertextris                r   export_to_plyrM   +   s    "55VDIIZZ $$&,,.FJJNN""$E
((ERqD((+22488:@@BRYZ
[C	ot4	5 $5		45	F}B7AB	%&	%&	%&?GG+,GG-.GG,-GGEM#e*R8'BCGG=>	 ?='')005C #&MMOJJL#E3 %#H  ]]7+F  ,T*+, ]]5)F --/ .V,-. ]]6*F||~ 5CH3s345G$5L Q S(%$5L s'   A L<2EMMCMMMoutput_obj_pathc                    | t        j                  d      j                  }| j                  j	                         j                         j                         }| j                  j                         j                         }t        j                  dD cg c];  }| j                  |   j	                         j                         j                         = c}d      }t        |j                         |j                               D cg c]  \  }} dj                  g ||  }}}|j                         D 	cg c]B  }	dj                  t        |	d   dz         t        |	d   dz         t        |	d	   dz               D }}	|D 
cg c]  }
d
|
z   	 c}
|z   }t        |d      5 }|j!                  dj#                  |             d d d        y c c}w c c}}w c c}	w c c}
w # 1 sw Y   y xY w)Nz.objr   r)   r   r*   z{} {} {} {} {} {}z
f {} {} {}r      zv wr-   )r!   r"   r#   r/   r0   r1   r2   r3   r4   r5   r6   r>   r?   rI   strr7   
writelinesjoin)rC   rN   r/   r3   rE   vertex_colorsrG   colorrH   rL   rK   combined_datar   s                r   export_to_objrX   _   s   "55VDIIJJ##%++-EJJNN""$EHHV[\QRd2215<<>BBDJJL\cdeMGJ5<<>[h[o[o[qGr7Cue"""2E2E2H  `e_k_k_mnX[\  SVaZ#c!fqj/3s1vPQz?SnEn19:vTF]:UBM	os	# /q	TYY}-./ / ] o:/ /s&   A GG;AGG &!G%%G.video_framesoutput_video_pathc                    t               rdd l}n$t        t        d   d   j	                  d            | t        j                  d      j                  }t        | d   t        j                        r0| D cg c]$  }|dz  j                  t        j                        & } }nIt        | d   t        j                  j                        r"| D cg c]  }t        j                  |       } } |j                   d }| d   j"                  \  }}}|j%                  |||||f	      }	t'        t)        |             D ]2  }
|j+                  | |
   |j,                        }|	j/                  |       4 |S c c}w c c}w )
Nr   opencvr   export_to_video.mp4r      mp4v)r   	frameSize)r
   cv2ImportErrorr   rI   r!   r"   r#   
isinstancer4   ndarrayr<   uint8PILImagearrayVideoWriter_fourccshapeVideoWriterranger:   cvtColorCOLOR_RGB2BGRr8   )rY   rZ   r   rb   framefourcchrQ   cvideo_writeriimgs               r   _legacy_export_to_videorw   s   sO    *84Q7>>?PQRR $77vFKK,q/2::.DPQ5,,RXX6QQ	LOSYY__	55ABEBB#S##V,F1o##GAq!??#4f#RSUVQW?XL3|$%  ll<?C,=,=>3   R Cs   7)E0E5qualitybitratemacro_block_sizec                 L   t               s"t        j                  d       t        | ||      S t               rddl}n$t        t        d   d   j                  d            	 |j                  j                  j                          | t        j                  d	      j                  }t        | d   t         j"                        r0| D cg c]$  }|d
z  j%                  t         j&                        & } }nIt        | d   t(        j*                  j*                        r"| D cg c]  }t!        j,                  |       } }|j/                  |||||      5 }| D ]  }|j1                  |        	 ddd       |S # t        $ r t        d      w xY wc c}w c c}w # 1 sw Y   |S xY w)a  
    quality:
        Video output quality. Default is 5. Uses variable bit rate. Highest quality is 10, lowest is 0. Set to None to
        prevent variable bitrate flags to FFMPEG so you can manually specify them using output_params instead.
        Specifying a fixed bitrate using `bitrate` disables this parameter.

    bitrate:
        Set a constant bitrate for the video encoding. Default is None causing `quality` parameter to be used instead.
        Better quality videos with smaller file sizes will result from using the `quality` variable bitrate parameter
        rather than specifying a fixed bitrate with this parameter.

    macro_block_size:
        Size constraint for video. Width and height, must be divisible by this number. If not divisible by this number
        imageio will tell ffmpeg to scale the image up to the next closest size divisible by this number. Most codecs
        are compatible with a macroblock size of 16 (default), some can go smaller (4, 8). To disable this automatic
        feature set it to None or 1, however be warned many players can't decode videos that are odd in size and some
        codecs will produce poor results or fail. See https://en.wikipedia.org/wiki/Macroblock.
    a  It is recommended to use `export_to_video` with `imageio` and `imageio-ffmpeg` as a backend. 
These libraries are not present in your environment. Attempting to use legacy OpenCV backend to export video. 
Support for the OpenCV backend will be deprecated in a future Diffusers versionr   Nimageior   r]   zFound an existing imageio backend in your environment. Attempting to export video with imageio. 
Unable to find a compatible ffmpeg installation in your environment to use with imageio. Please install via `pip install imageio-ffmpegr^   r   r_   )r   rx   ry   rz   )r	   loggerwarningrw   r|   rc   r   rI   pluginsffmpegget_exeAttributeErrorr!   r"   r#   rd   r4   re   r<   rf   rg   rh   ri   
get_writerappend_data)	rY   rZ   r   rx   ry   rz   r|   rp   writers	            r   r]   r]      s   8  !b	
 '|5FLL*95a8??@QRSS
&&(  $77vFKK,q/2::.DPQ5,,RXX6QQ	LOSYY__	55ABEBB			sGWWg 
 
 &	! 	&Eu%	&& /  
Z
 	

 R C& s$   !$E7 )FFF7FF#)N
   r   )Nr   g      @N   )$r   randomr@   r!   
contextlibr   typingr   r   r   r2   r4   	PIL.Imagerg   PIL.ImageOpsimport_utilsr   r	   r
   loggingr   Random
global_rng__name__r}   r   rh   rR   r=   r%   rM   rX   re   rw   floatr]    r&   r   <module>r      sn   	    % ( (    U U  V]]_
	H	  ciioo.  RU _b 1 1h/ /* moRZZ($syy*??@UXfi8 "!&(DRZZ($syy*??@DD 
D 	D
 c]D smD 	Dr&   