
    Z j>                     L   S SK r S SKrS SKrS SKJs  Js  Jr  SSK	J
r
  SSKJr  SSKJrJrJrJr  SSKJrJrJrJrJr  SSKJrJrJrJr  SSKJr  S	S
KJ r   S	SK!J"r"  \" 5       (       a  S SK#J$r%  S r&S r'S r(\ " S S\ 5      5       r)\\" SS9 " S S\"5      5       5       r*SS/r+g)    N   )TorchvisionBackend)BatchFeature)group_images_by_shapepadreorder_imagesto_channel_dimension_format)OPENAI_CLIP_MEANOPENAI_CLIP_STDChannelDimensionPILImageResamplingSizeDict)
TensorTypeauto_docstringis_scipy_availablerequires_backends)requires   )OwlViTImageProcessor)OwlViTImageProcessorPil)ndimagec                 F   [        U5      n[        U5      nU R                  nX R                  :  a-  USX R                  -
  -  -  n[        R
                  " X5      n X4$ X R                  S-
  :X  a  XR                  S   4-   nX4$ X R                  :  a  [        S5      eX4$ )a  Validate resize output shape according to input image.

Args:
    image (`np.ndarray`):
     Image to be resized.
    output_shape (`iterable`):
        Size of the generated output image `(rows, cols[, ...][, dim])`. If `dim` is not provided, the number of
        channels is preserved.

Returns
    image (`np.ndarray`):
        The input image, but with additional singleton dimensions appended in the case where `len(output_shape) >
        input.ndim`.
    output_shape (`Tuple`):
        The output shape converted to tuple.

Raises ------ ValueError:
    If output_shape length is smaller than the image number of dimensions.

Notes ----- The input image is reshaped if its number of dimensions is not equal to output_shape_length.

)   r   zIoutput_shape length cannot be smaller than the image number of dimensions)tuplelenshapendimnpreshape
ValueError)imageoutput_shapeoutput_ndiminput_shapes       x/root/GenerationalWealth/GenerationalWealth/venv/lib/python3.13/site-packages/transformers/models/owlv2/modular_owlv2.py_preprocess_resize_output_shaper'   3   s    . &Ll#K++KZZt{ZZ788

5.  


Q	&#{{2&88  
zz	!dee    c                 8   [         R                  " U 5      n[         R                  " U5      (       a)  [         R                  n[         R                  nU" U 5      nO [         R                  n[         R
                  nU" U 5      n[         R                  " XU5      nU$ )a  Clip output image to range of values of input image.

Note that this function modifies the values of *output_image* in-place.

Taken from:
https://github.com/scikit-image/scikit-image/blob/b4b521d6f0a105aabeaa31699949f78453ca3511/skimage/transform/_warps.py#L640.

Args:
    input_image : ndarray
        Input image.
    output_image : ndarray
        Output image, which is modified in-place.
)r   minisnannanminnanmaxmaxclip)input_imageoutput_imagemin_valmin_funcmax_funcmax_vals         r&   _clip_warp_outputr6   Z   so     ff[!G	xx9999;'6666{#G77<':Lr(   c                 (   [        U[        [        45      (       aS  [        R                  " U Vs/ s H  o"S   PM	     sn5      n[        R                  " U Vs/ s H  o"S   PM	     sn5      nO>[        U[        R
                  5      (       a  UR                  S5      u  p4O[        S5      e[        R                  " X45      n[        R                  " XUXU/SS9nUR                  S5      R                  U R                  5      nX-  n U $ s  snf s  snf )a  
Scale batch of bounding boxes to the target sizes.

Args:
    boxes (`torch.Tensor` of shape `(batch_size, num_boxes, 4)`):
        Bounding boxes to scale. Each box is expected to be in (x1, y1, x2, y2) format.
    target_sizes (`list[tuple[int, int]]` or `torch.Tensor` of shape `(batch_size, 2)`):
        Target sizes to scale the boxes to. Each target size is expected to be in (height, width) format.

Returns:
    `torch.Tensor` of shape `(batch_size, num_boxes, 4)`: Scaled bounding boxes.
r   r   z4`target_sizes` must be a list, tuple or torch.Tensor)dim)
isinstancelistr   torchtensorTensorunbind	TypeErrorr.   stack	unsqueezetodevice)boxestarget_sizesiimage_heightimage_widthmax_sizescale_factors          r&   _scale_boxesrK   x   s     ,u..||<$@<aqT<$@All,#?,QaD,#?@	L%,,	/	/$0$7$7$:!kNOO yy3H;;HGQOL))!,//=L EL %A#?s   D
Dc                   B   \ rS rSr\R
                  r\r\	r
SSS.rSrSrSrSrSrSrSrSSSS	\S
S4S jjr SS\S   S\S-  S	\S
\S   4S jjr  SSSS\S\S
S4S jjrS\S   S\S\SSS\S\S\S\S\\\   -  S-  S\\\   -  S-  S\S-  S\\-  S-  S
\4S jrSrg) Owlv2ImageProcessor     heightwidthp?TNimagesztorch.Tensorconstant_valuereturnc                     UR                   SS u  p4[        X45      nXS-
  nXT-
  nSSXv4n[        R                  " XUS9n	U	$ ),
Pad an image with zeros to the given size.
Nr   )fill)r   r.   tvFr   )
selfrT   rU   rQ   rR   size
pad_bottom	pad_rightpaddingpadded_images
             r&   _pad_imagesOwlv2ImageProcessor._pad_images   sP     RS)6!]
L	a/wwv^Dr(   disable_groupingc                     [        XS9u  pV0 nUR                  5        H  u  pU R                  U	US9n	XU'   M     [        Xv5      n
U
$ )zx
Unlike the Base class `self.pad` where all images are padded to the maximum image size,
Owlv2 pads an image to square.
rd   )rU   )r   itemsrb   r   )r\   rT   rd   rU   kwargsgrouped_imagesgrouped_images_indexprocessed_images_groupedr   stacked_imagesprocessed_imagess              r&   r   Owlv2ImageProcessor.pad   sg     0EV/o,#% %3%9%9%;!E!--- . N /=U+ &< **BYr(   r"   r]   anti_aliasingc                    UR                   UR                  4nUR                  n[        R                  " USS 5      R                  UR                  5      [        R                  " U5      R                  UR                  5      -  nU(       Ga#  Uc  US-
  S-  R                  SS9nO[        R                  " U5      [        R                  " U5      -  n[        R                  " US:  5      (       a  [        S5      e[        R                  " US:  US:*  -  5      (       a  [        R                  " S5        [        R                  " US:H  5      (       a  Un	O[S[        R                  " SU-  5      R                  5       -  S-   n
[         R"                  " XS   U
S   4UR%                  5       S	9n	OUn	[&        R(                  " XS
S9$ )a  
Resize an image as per the original implementation.

Args:
    image (`Tensor`):
        Image to resize.
    size (`dict[str, int]`):
        Dictionary containing the height and width to resize the image to.
    anti_aliasing (`bool`, *optional*, defaults to `True`):
        Whether to apply anti-aliasing when downsampling the image.
    anti_aliasing_sigma (`float`, *optional*, defaults to `None`):
        Standard deviation for Gaussian kernel when downsampling the image. If `None`, it will be calculated
        automatically.
r   Nr   r   )r*   FAnti-aliasing standard deviation must be greater than or equal to zeroWAnti-aliasing standard deviation greater than zero but not down-sampling along all axesr   )sigmaF)r]   	antialias)rQ   rR   r   r;   r<   rB   rC   clamp
atleast_1d	ones_likeanyr!   warningswarnceilintr[   gaussian_blurtolistr   resize)r\   r"   r]   ro   anti_aliasing_sigmarh   r#   r%   factorsfilteredkernel_sizess              r&   r   Owlv2ImageProcessor.resize   s   , TZZ0kk ,,{12/225<<@5<<P\C]C`C`afamamCnn"*(/!q'8&?&?A&?&F#&+&6&67J&Keoo^eNf&f#9901455$%mnnYY 3a 7GqLIJJMMq yy,122  5::a2E.E#F#J#J#LLqP,,O\!_=EXE_E_Ea
 H!((NNr(   	do_resizeresamplePILImageResampling | Nonedo_pad
do_rescalerescale_factordo_normalize
image_mean	image_stdreturn_tensorsc           	          [        XS9u  p0 nUR                  5        H  u  nnU R                  UXgSX5      nUUU'   M!     [        UU5      nU(       a  U R	                  USUS9n[        UUS9u  p0 nUR                  5        H$  u  nnU(       d  M  U R                  UX4S9nUUU'   M&     [        UU5      n[        UUS9u  p0 nUR                  5        H  u  nnU R                  USXxX5      nUUU'   M!     [        UU5      n[        SU0US9$ )Nrf   F        )rU   rd   )r"   r]   r   pixel_valuesdatatensor_type)r   rg   rescale_and_normalizer   r   r   r   )r\   rT   r   r]   r   r   r   r   r   r   r   rd   r   rh   ri   rj   rk   r   rl   rm   resized_images_groupedresized_stackresized_imagess                          r&   _preprocessOwlv2ImageProcessor._preprocess   sb   " 0EV/o,#% %3%9%9%;!E>!77
E:N /=$U+ &< **BDXY#xx(8_oxp/D/?0
, "$%3%9%9%;!E>y $.t _0=&u- &< ((>@TU 0E^fv/w,#% %3%9%9%;!E>!77~ZN /=$U+ &< **BDXY.2B!CQ_``r(    r   TN)__name__
__module____qualname____firstlineno__r   BILINEARr   r
   r   r   r   r]   r   r   r   r   r   	crop_sizedo_center_cropfloatrb   r:   boolr   r   r   strr   r   r   __static_attributes__r   r(   r&   rM   rM      s   !**H!JIC(DNIJLFIN. % R` " !$	 ^$  +  	  
n	 8 # 4O4O 4O 	4O 
4Ol7a^$7a 7a 	7a
 .7a 7a 7a 7a 7a DK'$.7a 4;&-7a +7a j(4/7a 
7ar(   rM   )r;   )backendsc                   t   \ rS rSr\R
                  r\r\	r
SSS.rSrSrSrSrSrSrSrSS\R(                  S\S	\R(                  4S
 jjr  SS\R(                  S\\\4   S\S	\R(                  4S jjrS\\R(                     S\S\SSS\S\S\S\S\\\   -  S-  S\\\   -  S-  S\\-  S-  S	\4S jr Sr!g)Owlv2ImageProcessorPili:  rO   rP   rS   TNr"   rU   rV   c                 p    UR                   SS u  p4[        X45      nXS-
  nXT-
  n[        USU4SU44US9nU$ )rX   rY   Nr   )r"   r`   constant_values)r   r.   r   )r\   r"   rU   rQ   rR   r]   r^   r_   s           r&   r   Owlv2ImageProcessorPil.padI  sU     BC(6!]
L	_q)n5*

 r(   r]   ro   c           	         [        U S5        US   US   4n[        U[        R                  5      n[	        X5      u  pUR
                  n[        R                  " Xv5      nSn	Sn
SnU(       a  Uc  [        R                  " SUS-
  S-  5      nO[        R                  " U5      [        R                  " U5      -  n[        R                  " US:  5      (       a  [        S5      e[        R                  " US:  US:*  -  5      (       a  [        R                  " S	5        [        R                   " XXS
9nOUnU Vs/ s H  nSU-  PM
     nn[        R"                  " XXU
SS9n[%        X5      n[        U[        R&                  5      nU$ s  snf )a  
Resize an image as per the original implementation.

Args:
    image (`np.ndarray`):
        Image to resize.
    size (`dict[str, int]`):
        Dictionary containing the height and width to resize the image to.
    anti_aliasing (`bool`, *optional*, defaults to `True`):
        Whether to apply anti-aliasing when downsampling the image.
    anti_aliasing_sigma (`float`, *optional*, defaults to `None`):
        Standard deviation for Gaussian kernel when downsampling the image. If `None`, it will be calculated
        automatically.
scipyrQ   rR   mirrorr   r   r   rq   rr   )cvalmodeT)orderr   r   	grid_mode)r   r	   r   LASTr'   r   r   dividemaximumrv   rw   rx   r!   ry   rz   ndigaussian_filterzoomr6   FIRST)r\   r"   r]   ro   r   rh   r#   r%   r   ndi_moder   r   r   fzoom_factorsouts                   r&   r   Owlv2ImageProcessorPil.resizeX  sf   , 	$(XW6+E3C3H3HI=eRkk))K6 "*&(jjWq[A4E&F#&(mm4G&H2<<X_K`&`#66-122$%mnnVV014AFGGMMq **5D`HH'./w!Aw/hhxUPT`de!%-+E3C3I3IJ 0s   :F	rT   r   r   r   r   r   r   r   r   r   r   c                    / nU Hv  nU(       a  U R                  X5      nU(       a  U R                  U5      nU(       a  U R                  XU5      nU(       a  U R                  XU
5      nUR	                  U5        Mx     [        SU0US9$ )Nr   r   )rescaler   r   	normalizeappendr   )r\   rT   r   r]   r   r   r   r   r   r   r   r   rh   rm   r"   s                  r&   r   "Owlv2ImageProcessorPil._preprocess  s     EU;E:u)D##E*  .2B!CQ_``r(   r   r   r   )"r   r   r   r   r   r   r   r
   r   r   r   r]   r   r   r   r   r   r   r   r   ndarrayr   r   dictr   r|   r   r   r:   r   r   r   r   r   r   r(   r&   r   r   :  sc    "**H!JIC(DNIJLFIN U RZZ & # 7zz7 38n7 	7 
7raRZZ a a 	a
 .a a a a a DK'$.a 4;&-a j(4/a 
ar(   r   ),ry   numpyr   r;   $torchvision.transforms.v2.functional
transformsv2
functionalr[   image_processing_backendsr   image_processing_utilsr   image_transformsr   r   r   r	   image_utilsr
   r   r   r   r   utilsr   r   r   r   utils.import_utilsr   owlvit.image_processing_owlvitr   "owlvit.image_processing_pil_owlvitr   r   r   r   r'   r6   rK   rM   r   __all__r   r(   r&   <module>r      s       2 2 ; 2    + A H $$N<> _a. _a _aD 	:oa4 oa  oad !":
;r(   