


import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
		import torch

if is_vision_available():
		from PIL import Image

		from transformers import ChineseCLIPImageProcessor


class 						lowerCamelCase       (unittest.TestCase      ):







							"""simple docstring"""




							def __init__( self     :					str,			_UpperCAmelCase     :					Optional[Any],			_UpperCAmelCase     :					int=7,			_UpperCAmelCase     :					int=3,			_UpperCAmelCase     :					Dict=1_8,			_UpperCAmelCase     :					int=3_0,			_UpperCAmelCase     :					Optional[Any]=4_0_0,			_UpperCAmelCase     :					Dict=True,			_UpperCAmelCase     :					Optional[int]=None,			_UpperCAmelCase     :					int=True,			_UpperCAmelCase     :					List[Any]=None,			_UpperCAmelCase     :					Dict=True,			_UpperCAmelCase     :					Dict=[0.48145466, 0.4578275, 0.40821073],			_UpperCAmelCase     :					Dict=[0.26862954, 0.26130258, 0.27577711],			_UpperCAmelCase     :					Any=True,			)				->			Optional[Any]:





														"""simple docstring"""
														SCREAMING_SNAKE_CASE__       :      Any     =						size if size is not None else {"height": 2_2_4, "width": 2_2_4}
														SCREAMING_SNAKE_CASE__       :      Optional[Any]     =						crop_size if crop_size is not None else {"height": 1_8, "width": 1_8}
														SCREAMING_SNAKE_CASE__       :      str     =						parent
														SCREAMING_SNAKE_CASE__       :      Dict     =						batch_size
														SCREAMING_SNAKE_CASE__       :      Optional[int]     =						num_channels
														SCREAMING_SNAKE_CASE__       :      int     =						image_size
														SCREAMING_SNAKE_CASE__       :      Optional[Any]     =						min_resolution
														SCREAMING_SNAKE_CASE__       :      Optional[int]     =						max_resolution
														SCREAMING_SNAKE_CASE__       :      str     =						do_resize
														SCREAMING_SNAKE_CASE__       :      int     =						size
														SCREAMING_SNAKE_CASE__       :      List[Any]     =						do_center_crop
														SCREAMING_SNAKE_CASE__       :      List[str]     =						crop_size
														SCREAMING_SNAKE_CASE__       :      int     =						do_normalize
														SCREAMING_SNAKE_CASE__       :      str     =						image_mean
														SCREAMING_SNAKE_CASE__       :      Optional[Any]     =						image_std
														SCREAMING_SNAKE_CASE__       :      Dict     =						do_convert_rgb






							def  A_     ( self     :					Optional[int]						)				->			Dict:





														"""simple docstring"""
														return {
														    "do_resize": self.do_resize,
														    "size": self.size,
														    "do_center_crop": self.do_center_crop,
														    "crop_size": self.crop_size,
														    "do_normalize": self.do_normalize,
														    "image_mean": self.image_mean,
														    "image_std": self.image_std,
														    "do_convert_rgb": self.do_convert_rgb,
														}






							def  A_     ( self     :					List[Any],			_UpperCAmelCase     :					Union[str, Any]=False,			_UpperCAmelCase     :					List[str]=False,			_UpperCAmelCase     :					Dict=False						)				->			Union[str, Any]:





														"""simple docstring"""
														assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

														if equal_resolution:
																					SCREAMING_SNAKE_CASE__       :      str     =						[]
																					for i in range(self.batch_size						):
																												image_inputs.append(
																												    np.random.randint(
																												        2_5_5,			size=(self.num_channels, self.max_resolution, self.max_resolution),			dtype=np.uinta						)						)
														else:
																					SCREAMING_SNAKE_CASE__       :      Optional[int]     =						[]
																					for i in range(self.batch_size						):
																												SCREAMING_SNAKE_CASE__   ,SCREAMING_SNAKE_CASE__       :      Optional[Any]     =						np.random.choice(np.arange(self.min_resolution,			self.max_resolution						),			2						)
																												image_inputs.append(np.random.randint(2_5_5,			size=(self.num_channels, width, height),			dtype=np.uinta						)						)

														if not numpify and not torchify:
																					# PIL expects the channel dimension as last dimension
																					SCREAMING_SNAKE_CASE__       :      Optional[Any]     =						[Image.fromarray(np.moveaxis(_lowerCamelCase,			0,			-1						)						) for x in image_inputs]

														if torchify:
																					SCREAMING_SNAKE_CASE__       :      List[str]     =						[torch.from_numpy(_lowerCamelCase						) for x in image_inputs]

														return image_inputs


@require_torch
@require_vision
class 						lowerCamelCase       (A_							,     unittest.TestCase      ):







							"""simple docstring"""




							UpperCAmelCase_      						=   ChineseCLIPImageProcessor if is_vision_available() else None






							def  A_     ( self     :					Tuple						)				->			int:





														"""simple docstring"""
														SCREAMING_SNAKE_CASE__       :      Dict     =						ChineseCLIPImageProcessingTester(self,			do_center_crop=_lowerCamelCase						)






							@property
							def  A_     ( self     :					List[str]						)				->			List[str]:





														"""simple docstring"""
														return self.image_processor_tester.prepare_image_processor_dict()






							def  A_     ( self     :					List[Any]						)				->			Dict:





														"""simple docstring"""
														SCREAMING_SNAKE_CASE__       :      Union[str, Any]     =						self.image_processing_class(**self.image_processor_dict						)
														self.assertTrue(hasattr(_lowerCamelCase,			"do_resize"						)						)
														self.assertTrue(hasattr(_lowerCamelCase,			"size"						)						)
														self.assertTrue(hasattr(_lowerCamelCase,			"do_center_crop"						)						)
														self.assertTrue(hasattr(_lowerCamelCase,			"center_crop"						)						)
														self.assertTrue(hasattr(_lowerCamelCase,			"do_normalize"						)						)
														self.assertTrue(hasattr(_lowerCamelCase,			"image_mean"						)						)
														self.assertTrue(hasattr(_lowerCamelCase,			"image_std"						)						)
														self.assertTrue(hasattr(_lowerCamelCase,			"do_convert_rgb"						)						)






							def  A_     ( self     :					int						)				->			Optional[Any]:





														"""simple docstring"""
														SCREAMING_SNAKE_CASE__       :      List[Any]     =						self.image_processing_class.from_dict(self.image_processor_dict						)
														self.assertEqual(image_processor.size,			{"height": 2_2_4, "width": 2_2_4}						)
														self.assertEqual(image_processor.crop_size,			{"height": 1_8, "width": 1_8}						)

														SCREAMING_SNAKE_CASE__       :      List[Any]     =						self.image_processing_class.from_dict(self.image_processor_dict,			size=4_2,			crop_size=8_4						)
														self.assertEqual(image_processor.size,			{"shortest_edge": 4_2}						)
														self.assertEqual(image_processor.crop_size,			{"height": 8_4, "width": 8_4}						)






							def  A_     ( self     :					str						)				->			int:





														"""simple docstring"""
														pass






							def  A_     ( self     :					List[str]						)				->			int:





														"""simple docstring"""
														# Initialize image_processing
														SCREAMING_SNAKE_CASE__       :      List[Any]     =						self.image_processing_class(**self.image_processor_dict						)
														# create random PIL images
														SCREAMING_SNAKE_CASE__       :      Optional[int]     =						self.image_processor_tester.prepare_inputs(equal_resolution=_lowerCamelCase						)
														for image in image_inputs:
																					self.assertIsInstance(_lowerCamelCase,			Image.Image						)

														# Test not batched input
														SCREAMING_SNAKE_CASE__       :      Union[str, Any]     =						image_processing(image_inputs[0],			return_tensors="pt"						).pixel_values
														self.assertEqual(
														    encoded_images.shape,			(
														        1,
														        self.image_processor_tester.num_channels,
														        self.image_processor_tester.crop_size["height"],
														        self.image_processor_tester.crop_size["width"],
														    ),			)

														# Test batched
														SCREAMING_SNAKE_CASE__       :      Optional[Any]     =						image_processing(_lowerCamelCase,			return_tensors="pt"						).pixel_values
														self.assertEqual(
														    encoded_images.shape,			(
														        self.image_processor_tester.batch_size,
														        self.image_processor_tester.num_channels,
														        self.image_processor_tester.crop_size["height"],
														        self.image_processor_tester.crop_size["width"],
														    ),			)






							def  A_     ( self     :					Optional[int]						)				->			List[str]:





														"""simple docstring"""
														# Initialize image_processing
														SCREAMING_SNAKE_CASE__       :      Tuple     =						self.image_processing_class(**self.image_processor_dict						)
														# create random numpy tensors
														SCREAMING_SNAKE_CASE__       :      Optional[Any]     =						self.image_processor_tester.prepare_inputs(equal_resolution=_lowerCamelCase,			numpify=_lowerCamelCase						)
														for image in image_inputs:
																					self.assertIsInstance(_lowerCamelCase,			np.ndarray						)

														# Test not batched input
														SCREAMING_SNAKE_CASE__       :      List[Any]     =						image_processing(image_inputs[0],			return_tensors="pt"						).pixel_values
														self.assertEqual(
														    encoded_images.shape,			(
														        1,
														        self.image_processor_tester.num_channels,
														        self.image_processor_tester.crop_size["height"],
														        self.image_processor_tester.crop_size["width"],
														    ),			)

														# Test batched
														SCREAMING_SNAKE_CASE__       :      int     =						image_processing(_lowerCamelCase,			return_tensors="pt"						).pixel_values
														self.assertEqual(
														    encoded_images.shape,			(
														        self.image_processor_tester.batch_size,
														        self.image_processor_tester.num_channels,
														        self.image_processor_tester.crop_size["height"],
														        self.image_processor_tester.crop_size["width"],
														    ),			)






							def  A_     ( self     :					Dict						)				->			Dict:





														"""simple docstring"""
														# Initialize image_processing
														SCREAMING_SNAKE_CASE__       :      List[str]     =						self.image_processing_class(**self.image_processor_dict						)
														# create random PyTorch tensors
														SCREAMING_SNAKE_CASE__       :      int     =						self.image_processor_tester.prepare_inputs(equal_resolution=_lowerCamelCase,			torchify=_lowerCamelCase						)
														for image in image_inputs:
																					self.assertIsInstance(_lowerCamelCase,			torch.Tensor						)

														# Test not batched input
														SCREAMING_SNAKE_CASE__       :      List[str]     =						image_processing(image_inputs[0],			return_tensors="pt"						).pixel_values
														self.assertEqual(
														    encoded_images.shape,			(
														        1,
														        self.image_processor_tester.num_channels,
														        self.image_processor_tester.crop_size["height"],
														        self.image_processor_tester.crop_size["width"],
														    ),			)

														# Test batched
														SCREAMING_SNAKE_CASE__       :      Tuple     =						image_processing(_lowerCamelCase,			return_tensors="pt"						).pixel_values
														self.assertEqual(
														    encoded_images.shape,			(
														        self.image_processor_tester.batch_size,
														        self.image_processor_tester.num_channels,
														        self.image_processor_tester.crop_size["height"],
														        self.image_processor_tester.crop_size["width"],
														    ),			)


@require_torch
@require_vision
class 						lowerCamelCase       (A_							,     unittest.TestCase      ):







							"""simple docstring"""




							UpperCAmelCase_      						=   ChineseCLIPImageProcessor if is_vision_available() else None






							def  A_     ( self     :					Dict						)				->			Optional[int]:





														"""simple docstring"""
														SCREAMING_SNAKE_CASE__       :      Tuple     =						ChineseCLIPImageProcessingTester(self,			num_channels=4,			do_center_crop=_lowerCamelCase						)
														SCREAMING_SNAKE_CASE__       :      int     =						3






							@property
							def  A_     ( self     :					Union[str, Any]						)				->			List[Any]:





														"""simple docstring"""
														return self.image_processor_tester.prepare_image_processor_dict()






							def  A_     ( self     :					Dict						)				->			Optional[Any]:





														"""simple docstring"""
														SCREAMING_SNAKE_CASE__       :      Any     =						self.image_processing_class(**self.image_processor_dict						)
														self.assertTrue(hasattr(_lowerCamelCase,			"do_resize"						)						)
														self.assertTrue(hasattr(_lowerCamelCase,			"size"						)						)
														self.assertTrue(hasattr(_lowerCamelCase,			"do_center_crop"						)						)
														self.assertTrue(hasattr(_lowerCamelCase,			"center_crop"						)						)
														self.assertTrue(hasattr(_lowerCamelCase,			"do_normalize"						)						)
														self.assertTrue(hasattr(_lowerCamelCase,			"image_mean"						)						)
														self.assertTrue(hasattr(_lowerCamelCase,			"image_std"						)						)
														self.assertTrue(hasattr(_lowerCamelCase,			"do_convert_rgb"						)						)






							def  A_     ( self     :					List[Any]						)				->			Tuple:





														"""simple docstring"""
														pass






							def  A_     ( self     :					Union[str, Any]						)				->			Optional[Any]:





														"""simple docstring"""
														# Initialize image_processing
														SCREAMING_SNAKE_CASE__       :      Optional[int]     =						self.image_processing_class(**self.image_processor_dict						)
														# create random PIL images
														SCREAMING_SNAKE_CASE__       :      List[Any]     =						self.image_processor_tester.prepare_inputs(equal_resolution=_lowerCamelCase						)
														for image in image_inputs:
																					self.assertIsInstance(_lowerCamelCase,			Image.Image						)

														# Test not batched input
														SCREAMING_SNAKE_CASE__       :      int     =						image_processing(image_inputs[0],			return_tensors="pt"						).pixel_values
														self.assertEqual(
														    encoded_images.shape,			(
														        1,
														        self.expected_encoded_image_num_channels,
														        self.image_processor_tester.crop_size["height"],
														        self.image_processor_tester.crop_size["width"],
														    ),			)

														# Test batched
														SCREAMING_SNAKE_CASE__       :      int     =						image_processing(_lowerCamelCase,			return_tensors="pt"						).pixel_values
														self.assertEqual(
														    encoded_images.shape,			(
														        self.image_processor_tester.batch_size,
														        self.expected_encoded_image_num_channels,
														        self.image_processor_tester.crop_size["height"],
														        self.image_processor_tester.crop_size["width"],
														    ),			)













import sys
from typing import Tuple

import numpy as np
import torch
from PIL import Image
from torch import nn

from transformers.image_utils import PILImageResampling
from utils import img_tensorize


class 						lowerCamelCase       :







							"""simple docstring"""




							def __init__( self     :					Dict,			_UpperCAmelCase     :					Any,			_UpperCAmelCase     :					List[Any]=sys.maxsize						)				->			Optional[int]:





														"""simple docstring"""
														SCREAMING_SNAKE_CASE__       :      Optional[int]     =						"bilinear"
														SCREAMING_SNAKE_CASE__       :      Optional[int]     =						max_size
														SCREAMING_SNAKE_CASE__       :      Optional[int]     =						short_edge_length






							def __call__( self     :					Optional[int],			_UpperCAmelCase     :					Union[str, Any]						)				->			str:





														"""simple docstring"""
														SCREAMING_SNAKE_CASE__       :      List[Any]     =						[]
														for img in imgs:
																					SCREAMING_SNAKE_CASE__   ,SCREAMING_SNAKE_CASE__       :      Tuple     =						img.shape[:2]
																					# later: provide list and randomly choose index for resize
																					SCREAMING_SNAKE_CASE__       :      List[str]     =						np.random.randint(self.short_edge_length[0],			self.short_edge_length[1] + 1						)
																					if size == 0:
																												return img
																					SCREAMING_SNAKE_CASE__       :      int     =						size * 1.0 / min(_UpperCAmelCase,			_UpperCAmelCase						)
																					if h < w:
																												SCREAMING_SNAKE_CASE__   ,SCREAMING_SNAKE_CASE__       :      Optional[int]     =						size, scale * w
																					else:
																												SCREAMING_SNAKE_CASE__   ,SCREAMING_SNAKE_CASE__       :      List[str]     =						scale * h, size
																					if max(_UpperCAmelCase,			_UpperCAmelCase						) > self.max_size:
																												SCREAMING_SNAKE_CASE__       :      str     =						self.max_size * 1.0 / max(_UpperCAmelCase,			_UpperCAmelCase						)
																												SCREAMING_SNAKE_CASE__       :      Any     =						newh * scale
																												SCREAMING_SNAKE_CASE__       :      List[str]     =						neww * scale
																					SCREAMING_SNAKE_CASE__       :      Any     =						int(neww + 0.5						)
																					SCREAMING_SNAKE_CASE__       :      List[Any]     =						int(newh + 0.5						)

																					if img.dtype == np.uinta:
																												SCREAMING_SNAKE_CASE__       :      List[Any]     =						Image.fromarray(_UpperCAmelCase						)
																												SCREAMING_SNAKE_CASE__       :      Union[str, Any]     =						pil_image.resize((neww, newh),			PILImageResampling.BILINEAR						)
																												SCREAMING_SNAKE_CASE__       :      List[str]     =						np.asarray(_UpperCAmelCase						)
																					else:
																												SCREAMING_SNAKE_CASE__       :      str     =						img.permute(2,			0,			1						).unsqueeze(0						)  # 3, 0, 1)  # hw(c) -> nchw
																												SCREAMING_SNAKE_CASE__       :      Tuple     =						nn.functional.interpolate(
																												    _UpperCAmelCase,			(newh, neww),			mode=self.interp_method,			align_corners=_UpperCAmelCase						).squeeze(0						)
																					img_augs.append(_UpperCAmelCase						)

														return img_augs


class 						lowerCamelCase       :







							"""simple docstring"""




							def __init__( self     :					Dict,			_UpperCAmelCase     :					Optional[Any]						)				->			Optional[int]:





														"""simple docstring"""
														SCREAMING_SNAKE_CASE__       :      Any     =						ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST],			cfg.INPUT.MAX_SIZE_TEST						)
														SCREAMING_SNAKE_CASE__       :      Any     =						cfg.INPUT.FORMAT
														SCREAMING_SNAKE_CASE__       :      List[str]     =						cfg.SIZE_DIVISIBILITY
														SCREAMING_SNAKE_CASE__       :      List[Any]     =						cfg.PAD_VALUE
														SCREAMING_SNAKE_CASE__       :      Dict     =						cfg.INPUT.MAX_SIZE_TEST
														SCREAMING_SNAKE_CASE__       :      Optional[int]     =						cfg.MODEL.DEVICE
														SCREAMING_SNAKE_CASE__       :      int     =						torch.tensor(cfg.MODEL.PIXEL_STD						).to(self.device						).view(len(cfg.MODEL.PIXEL_STD						),			1,			1						)
														SCREAMING_SNAKE_CASE__       :      str     =						torch.tensor(cfg.MODEL.PIXEL_MEAN						).to(self.device						).view(len(cfg.MODEL.PIXEL_STD						),			1,			1						)
														SCREAMING_SNAKE_CASE__       :      Optional[Any]     =						lambda _UpperCAmelCase						: (x - self.pixel_mean) / self.pixel_std






							def  A_     ( self     :					str,			_UpperCAmelCase     :					Union[str, Any]						)				->			Union[str, Any]:





														"""simple docstring"""
														SCREAMING_SNAKE_CASE__       :      Tuple     =						tuple(max(_UpperCAmelCase						) for s in zip(*[img.shape for img in images]						)						)
														SCREAMING_SNAKE_CASE__       :      Optional[Any]     =						[im.shape[-2:] for im in images]
														SCREAMING_SNAKE_CASE__       :      Union[str, Any]     =						[
														    nn.functional.pad(
														        _UpperCAmelCase,			[0, max_size[-1] - size[1], 0, max_size[-2] - size[0]],			value=self.pad_value,			)
														    for size, im in zip(_UpperCAmelCase,			_UpperCAmelCase						)
														]

														return torch.stack(_UpperCAmelCase						), torch.tensor(_UpperCAmelCase						)






							def __call__( self     :					Any,			_UpperCAmelCase     :					Dict,			_UpperCAmelCase     :					List[str]=False						)				->			Optional[Any]:





														"""simple docstring"""
														with torch.no_grad():
																					if not isinstance(_UpperCAmelCase,			_UpperCAmelCase						):
																												SCREAMING_SNAKE_CASE__       :      str     =						[images]
																					if single_image:
																												assert len(_UpperCAmelCase						) == 1
																					for i in range(len(_UpperCAmelCase						)						):
																												if isinstance(images[i],			torch.Tensor						):
																																			images.insert(_UpperCAmelCase,			images.pop(_UpperCAmelCase						).to(self.device						).float()						)
																												elif not isinstance(images[i],			torch.Tensor						):
																																			images.insert(
																																			    _UpperCAmelCase,			torch.as_tensor(img_tensorize(images.pop(_UpperCAmelCase						),			input_format=self.input_format						)						)
																																			    .to(self.device						)
																																			    .float(),			)
            # resize smallest edge
																					SCREAMING_SNAKE_CASE__       :      List[str]     =						torch.tensor([im.shape[:2] for im in images]						)
																					SCREAMING_SNAKE_CASE__       :      Tuple     =						self.aug(_UpperCAmelCase						)
																					# transpose images and convert to torch tensors
																					# images = [torch.as_tensor(i.astype("float32")).permute(2, 0, 1).to(self.device) for i in images]
																					# now normalize before pad to avoid useless arithmetic
																					SCREAMING_SNAKE_CASE__       :      List[Any]     =						[self.normalizer(_UpperCAmelCase						) for x in images]
																					# now pad them to do the following operations
																					SCREAMING_SNAKE_CASE__   ,SCREAMING_SNAKE_CASE__       :      List[str]     =						self.pad(_UpperCAmelCase						)
																					# Normalize

																					if self.size_divisibility > 0:
																												raise NotImplementedError()
																					# pad
																					SCREAMING_SNAKE_CASE__       :      Union[str, Any]     =						torch.true_divide(_UpperCAmelCase,			_UpperCAmelCase						)
																					if single_image:
																												return images[0], sizes[0], scales_yx[0]
																					else:
																												return images, sizes, scales_yx




def _a (  SCREAMING_SNAKE_CASE__      :  int			,				SCREAMING_SNAKE_CASE__      :  Dict       )	->    Union[str, Any]:

							'''simple docstring'''






							boxes[:, 0::2] *= scale_yx[:, 1]
							boxes[:, 1::2] *= scale_yx[:, 0]
							return boxes







def _a (  SCREAMING_SNAKE_CASE__      :  List[Any]			,				SCREAMING_SNAKE_CASE__      :  Tuple[int, int]       )	->    List[Any]:

							'''simple docstring'''






							assert torch.isfinite(SCREAMING_SNAKE_CASE__       ).all(), "Box tensor contains infinite or NaN!"
							SCREAMING_SNAKE_CASE__   ,SCREAMING_SNAKE_CASE__       :      int     =						box_size
							tensor[:, 0].clamp_(min=0			,				max=SCREAMING_SNAKE_CASE__       )
							tensor[:, 1].clamp_(min=0			,				max=SCREAMING_SNAKE_CASE__       )
							tensor[:, 2].clamp_(min=0			,				max=SCREAMING_SNAKE_CASE__       )
							tensor[:, 3].clamp_(min=0			,				max=SCREAMING_SNAKE_CASE__       )






