
    ^j8                     J   d dl Zd dl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 ddlmZmZmZ ddlmZ dd	lmZmZmZ  e       rd dlmZ  ej:                  e      Zd
Z dZ!dZ"dZ#dZ$de%d   de%e&   fdZ'de&de(e&e&f   fdZ) G d ded      Z* G d de      Z+dgZ,y)    N)
functional   )BatchFeatureget_size_dict)IMAGENET_STANDARD_MEANIMAGENET_STANDARD_STDPILImageResamplingSizeDict)UnpackVideosKwargs)
TensorTypeis_torchvision_availablelogging)BaseVideoProcessor)VideoMetadatagroup_videos_by_shapereorder_videoszYou are a helpful language and vision assistant. You are able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language.zgYou are provided the following series of {frame_count} frames from a {video_duration} [H:MM:SS] video.
z

z
Frame from {timestamp}:i   videostorch.Tensorreturnc                     t        d      x}}| D ]0  }|j                         dd \  }}t        ||      }t        ||      }2 ||fS )zH
    Get the maximum height and width across all videos in a batch.
    z-infN)floatsizemax)r   
max_height	max_widthvideoheightwidths         /var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/smolvlm/video_processing_smolvlm.pyget_max_height_widthr"   0   s\     #6]*J *

RS),
y)	* 	""    resolution_max_sidec                 :   | j                         dd \  }}t        t        |      }|t        ||      n|}||z  }||k\  r|}t	        ||z        }|dz  dk7  r(|dz  }n"||kD  r|}t	        ||z        }|dz  dk7  r|dz  }t        |d      }t        |d      }||fS )a  
    Get the output size of the video after resizing given a dictionary specifying the max and min sizes.
    Args:
        video (`np.ndarray`):
            Video to resize.
        resolution_max_side (`int`):
            The longest edge of the video will be resized to this value. The shortest edge will be resized to keep the
            input aspect ratio.
    Returns:
        The output size of the video after resizing.
    r   N   r      )r   minMAX_IMAGE_SIZEr   int)r   r$   r   r    aspect_ratios        r!   get_resize_output_image_sizer,   <   s     JJL%MFE n.AB0C0K#fe,Qd6>L#U\)*A:?aKF	%$F\)*19>QJE^FqME5=r#   c                   "    e Zd ZU eeef   ed<   y)SmolVLMVideoProcessorInitKwargsmax_image_sizeN)__name__
__module____qualname__dictstrr*   __annotations__ r#   r!   r.   r.   d   s    cN"r#   r.   F)totalc                   z    e Zd Zej                  ZddiZddiZeZ	e
ZdZdZdZdZdZdZeZddgZdee   f fd	Z	 	 d(dddedddeddf
 fdZ	 	 d)dddeeef   dededef
dZ	 	 	 d*deded
z  deez  d
z  ded
z  fdZ	 d+de d   dedededdd ed!ed"ed#ed$ee e   z  d
z  d%ee e   z  d
z  d&e!e"z  d
z  fd'Z# xZ$S ),SmolVLMVideoProcessorlongest_edgei  il  TFpixel_valuespixel_attention_maskkwargsc                     t        |   di | d|v rd|v r|d   |d   d<   d|v r=|d   d   | _        |d   d   | _        t	        |d   d   | j
                        | _        y y )Nr   video_sampling
video_size
max_framesfps)default_to_squarer6   )super__init__
num_framesrB   r   rC   r   )selfr=   	__class__s     r!   rE   zSmolVLMVideoProcessor.__init__w   s    "6" V 0F :5;F^F#$\2v%$%56|DDO./6DH%f-=&>|&L`d`v`vwDI &r#   Nr   r   r   resamplez7PILImageResampling | tvF.InterpolationMode | int | None	antialiasr   c                    |j                   rt        ||j                         }n@|j                  r%|j                  r|j                  |j                  f}nt	        d| d      t
        |   |t        |d   |d         ||      }t        | j                  d   | j                  d         }t
        |   ||||      }|S )	a'  
        Resize an video to `(size["height"], size["width"])`.
        Args:
            video (`torch.Tensor`):
                Video to resize.
            size (`SizeDict`):
                Dictionary in the format `{"height": int, "width": int}` specifying the size of the output video.
            resample (`PILImageResampling` or `InterpolationMode`, *optional*, defaults to `InterpolationMode.BILINEAR`):
                Resampling filter to use when resizing the video.
        Returns:
            `torch.Tensor`: The resized video.
        )r$   zHSize must contain 'height' and 'width' keys, or 'longest_edge' key. Got .r   r'   )r   r    )rI   rJ   r:   )	r:   r,   r   r    
ValueErrorrD   resizer
   r/   )	rG   r   r   rI   rJ   r=   new_sizemax_sizerH   s	           r!   rN   zSmolVLMVideoProcessor.resize   s    (  4$($5$5H [[TZZTZZ0Hghlgmmnopp88A;hqkBXaj  
 4#6#6~#FdNaNabpNqruhYWr#   padded_sizemax_num_framesfillreturn_pixel_maskc                    |j                         dd }|j                  dk(  r|j                  d   n|j                  d   }|d   |d   z
  }|d   |d   z
  }	||z
  }
|	dk  s
|dk  s|
dk  rt        d| d| d| d	| d
	      ||k7  s|
dkD  r"d|	d|ddd|
g}t	        j
                  |||      }d}|rBt        j                  |ddddddf   t        j                        }d|dd|d   d|d   f<   ||fS )a*  Pads the sample with empty video to the padded_size
        Args:
            video (`torch.Tensor`):
                Batched video to pad.
            padded_size (`tuple[int, int]`):
                Height and width to pad.
            max_num_frames (`int`):
                The maximum number of frames to which video will be padded.
            fill (`int`, *optional*):
                The value to use for the padding.
            return_pixel_mask (`bool`, *optional*, defaults to `True`):
                Whether to return a pixel mask.
        r   N   r'   r   zPadding dimensions are negative. Please make sure that the padded size is larger than the original size. Got padded max number of frames z and padded size: z, original number of frames z and size: rL   )value.dtype)	r   ndimshaperM   Fpadtorch
zeros_likeint64)rG   r   rQ   rR   rS   rT   original_sizerF   padding_heightpadding_widthpadding_framepadding
pixel_masks                r!   r]   zSmolVLMVideoProcessor.pad   sQ   * 

RS)',zzQU[[^EKKN
$Q-*::#Aq)99&31 2ma6GBBPAQQcdocp q--7LM?RSU 
 K'=1+<-NAq!]SGEE%5E 
))%Q1*=U[[QJFGJs.mA..0B-2B0BBCj  r#   metadatarF   rB   	skip_secsc                 "   |t        |dd      t        d      ||n| j                  }||n| j                  }|j                  }t        t        ||d   z              }t        ||      }|dk  rd}d}	|dz
  }
|dkD  r6|d   d|z  z
  ||z  kD  r%t        ||d   z        }	t        |||d   z  z
        }
t        d|	      }	t        |
|dz
        }
|	|
k\  rd|dz
  }
}	t        j                  |	|
|t
              }t        j                  |      }|S )	a!  
        Video sampling function which:
            - Uses `num_frames` (if provided) or calculates it from `fps` and metadata.
            - Applies a basic center-skip if fewer frames than available, otherwise
                optionally skips `skip_secs` from both the start and end.
            - Uniformly samples the desired number of frames between the start and end indices.

        Args:
            metadata (`VideoMetadata`):
                Metadata of the video containing information about total duration, fps and total number of frames.
            num_frames (`int`, *optional*):
                Maximum number of frames to sample. Defaults to `self.num_frames`.
            fps (`int` or `float`, *optional*):
                Target frames to sample per second. Defaults to `self.fps`.
            skip_secs (`float`, *optional*, defaults to `1`):
                Number of seconds to skip from the start and end if the video is long enough.

        Returns:
            np.ndarray:
                Indices to sample video frames.
        NrB   zAsked to sample frames per second but no video metadata was provided which is required when sampling in SmolVLM. Please pass in `VideoMetadata` object or set `do_sample_frames=False`durationr'   r   r&   rX   )getattrrM   rF   rB   total_num_framesr*   roundr(   r   nplinspaceunique)rG   rg   rF   rB   rh   r=   rl   estimated_framesdesired_frames	start_idxend_idxindicess               r!   sample_framesz#SmolVLMVideoProcessor.sample_frames   sK   : wx=EX 
 $.#9Zt
_c$((#44 uS8J+?%?@A -z:AN 	"Q&q=hz2Q]BzTWGWXI78I*Y%-HHIG9%	g/!34!"$4q$8wI++i.L))G$r#   r   do_convert_rgb	do_resize
do_rescalerescale_factordo_normalizedo_pad
image_mean	image_stdreturn_tensorsc           	         t        |      \  }}i }|j                         D ]3  \  }}|r| j                  |      }|r| j                  |||      }|||<   5 t	        ||      }t        |      \  }}i }|j                         D ]   \  }}| j                  |||||
|      }|||<   " t	        ||      }|	rt        |      }t        d |D              }t        |      \  }}i }i }|j                         D ]&  \  }}| j                  |||      \  }}|||<   |||<   ( t	        ||      }t	        ||      }d|i}|	r |	r|t        j                  d      n|d<   t        ||      S )	N)r   rI   c              3   2   K   | ]  }t        |        y wN)len).0r   s     r!   	<genexpr>z4SmolVLMVideoProcessor._preprocess.<locals>.<genexpr>A  s      JU Js   )rQ   rR   r;   r   )dimr<   )tensor_type)r   itemsconvert_to_rgbrN   r   rescale_and_normalizer"   r   r]   r^   stackr   )rG   r   rw   rx   r   rI   ry   rz   r{   r|   r}   r~   r   r=   grouped_videosgrouped_videos_indexresized_videos_groupedr[   stacked_videosresized_videosprocessed_videos_groupedprocessed_videospad_sizerR   processed_padded_mask_groupedpadded_masksr<   datas                               r!   _preprocessz!SmolVLMVideoProcessor._preprocess  s     0EV/L,,!#%3%9%9%; 	;!E>!%!4!4^!D!%^$QY!Z,:"5)	; ((>@TU/D^/T,,#% %3%9%9%; 	=!E>!77
NL*V_N /=$U+		= **BDXY+,<=H  J9I JJN3HIY3Z0N0,.)')$)7)=)=)? D%~/3xx" 08 0, 3A(/7C-e4D  ..FH\]#12OQe#f  01 n8 0a8) '(
 Dn==r#   )NT)r   T)NNr'   r   )%r0   r1   r2   r	   LANCZOSrI   r   r/   r   r}   r   r~   rx   ry   r{   rw   r|   do_sample_framesr.   valid_kwargsmodel_input_namesr   rE   r
   boolrN   tupler*   r]   r   r   rv   listr4   r   r   __classcell__)rH   s   @r!   r9   r9   h   s   !))HG$D$c*N'J%IIJLNF2L')?@
x(G!H 
x  OS(( ( L	(
 ( 
(^ "&+!+! 38_+! 	+!
 +!  +!` "&"& !?? $J? 5[4	?
 :?\ 37=>^$=> => 	=>
 => L=> => => => => DK'$.=> 4;&-=> j(4/=>r#   r9   )-numpyrn   r^   torch.nnr   r\   image_processing_utilsr   r   image_utilsr   r   r	   r
   processing_utilsr   r   utilsr   r   r   video_processing_utilsr   video_utilsr   r   r   torchvision.transforms.v2tvF
get_loggerr0   loggerDEFAULT_SYSTEM_MESSAGEDEFAULT_VIDEO_INTRODEFAULT_MEDIA_OUTTROFRAME_TIMESTAMP_MESSAGEr)   r   r*   r"   r   r,   r.   r9   __all__r6   r#   r!   <module>r      s       $ A  5 B B 8 O O ; 
		H	% V n   5 	#n!5 	#$s) 	#%% 38_%P#l% #p>. p>f #
#r#   