o
    vi                  
   @   s   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	 d dl
mZ d dlmZ d dlmZ d dlmZ zd dlZW n eyS Z zee dZW Y dZ[ndZ[ww dd	d
Z	ddedeeee f deddfddZdS )    )IOAnyUnionN)	rearrange)Image)Tensor)log)easy_io   c                 C   sr   | d  tj} t| d} t|d|}| D ]}t|tj}|	| qW d    d S 1 s2w   Y  d S )N   )         r   Zh264)
astypenpuint8	transposeffmpegcvVideoWritercv2cvtColorCOLOR_RGB2BGRwrite)gridZ
video_namefpswriterframe r   S/data/cameron/vidgen/cosmos-policy/cosmos_policy/_src/imaginaire/visualize/video.py
save_video#   s   "r      sample_C_T_H_W_in01save_fp_wo_extr   returnc                 C   sx  | j dks	J dt|tst|dsJ dt| r#| dd} n| jtjks-J d| 	 
d} i }|d	ur>||d
< |d	urF||d< | jd dkrtjt|  	  d dtjdd}t|trjdnd}tj|t|trz| | n|fdddd| d	S t|  	  d dtj}t|trdnd}tj|t|tr| | n|fdd|d| d	S )aI  
    Save a tensor as an image or video file based on shape

        Args:
        sample_C_T_H_W_in01 (Tensor): Input tensor with shape (C, T, H, W) in [0, 1] range.
        save_fp_wo_ext (Union[str, IO[Any]]): File path without extension or file-like object.
        fps (int): Frames per second for video. Default is 24.
       zOnly support 4D tensorr   z3save_fp_wo_ext must be a string or file-like objectr   r   zOnly support uint8 tensorr   Nqualityffmpeg_paramszc 1 h w -> h w cRGB)modez.jpg jpgJPEGU   )file_formatformatr%   zc t h w -> t h w cz.mp4mp4)r-   r.   r   )ndim
isinstancestrhasattrtorchis_floating_pointclampdtyper   floatdivshapePILImage	fromarrayr   cpunumpyr   r   r	   dump)r!   r"   r   r%   r&   kwargsZsave_objextr   r   r   save_img_or_video-   sR   
 
"	
rB   )r
   )r    NN)typingr   r   r   r   r>   r   r4   einopsr   PILr   r;   r   #cosmos_policy._src.imaginaire.utilsr   +cosmos_policy._src.imaginaire.utils.easy_ior	   r   	Exceptioneinfor   r2   intrB   r   r   r   r   <module>   s6   

