





"""simple docstring"""



import colorsys
import io

import cva
import matplotlib as mpl
import matplotlib.colors as mplc
import matplotlib.figure as mplfigure
import numpy as np
import torch
from matplotlib.backends.backend_agg import FigureCanvasAgg

from utils import img_tensorize


a_				=    1000






class 	__snake_case      :





	"""simple docstring"""


	def __init__(					self      ,		__lowerCamelCase      ,		__lowerCamelCase=1.2      ,		__lowerCamelCase="g"      ,		__lowerCamelCase=0.5      ,		__lowerCamelCase="-"      ,		__lowerCamelCase="test_out.jpg"      ,		__lowerCamelCase=True      ,		__lowerCamelCase=False      ,		__lowerCamelCase=None      ,		__lowerCamelCase=None      ,		__lowerCamelCase=0.7      ,		):



					'''simple docstring'''




					if isinstance(_snake_case      ,		torch.Tensor						):
									__A					:		Tuple						=  img.numpy().astype('''np.uint8'''						)
					if isinstance(_snake_case      ,		_snake_case						):
									__A					:		Union[str, Any]						=  img_tensorize(_snake_case						)
					assert isinstance(_snake_case      ,		np.ndarray						)

					__A					:		List[Any]						=  img.shape[1], img.shape[0]
					__A					:		Optional[int]						=  mplfigure.Figure(frameon=_snake_case						)
					__A					:		Optional[Any]						=  fig.get_dpi()
					__A					:		Tuple						=  (width * scale + 1e-2) / dpi
					__A					:		Tuple						=  (height * scale + 1e-2) / dpi
					fig.set_size_inches(_snake_case      ,		_snake_case						)
					__A					:		Any						=  fig.add_axes([0.0, 0.0, 1.0, 1.0]						)
					ax.axis('''off'''						)
					ax.set_xlim(0.0      ,		_snake_case						)
					ax.set_ylim(_snake_case						)

					__A					:		str						=  saveas
					__A					:		Union[str, Any]						=  rgb
					__A					:		Dict						=  pynb
					__A					:		List[Any]						=  img
					__A					:		str						=  edgecolor
					__A					:		Dict						=  0.5
					__A					:		Dict						=  linestyle
					__A					:		Any						=  int(np.sqrt(min(_snake_case      ,		_snake_case						)						) * scale // 3						)
					__A					:		Tuple						=  width
					__A					:		List[Any]						=  height
					__A					:		List[Any]						=  scale
					__A					:		Tuple						=  fig
					__A					:		List[Any]						=  ax
					__A					:		Optional[int]						=  pad
					__A					:		List[str]						=  idaobj
					__A					:		Optional[int]						=  idaattr
					__A					:		List[str]						=  FigureCanvasAgg(_snake_case						)

	def       UpperCamelCase__(					self      ,		__lowerCamelCase      ,		__lowerCamelCase=None						):



					'''simple docstring'''




					if color is None:
									__A					:		List[Any]						=  self.edgecolor
					(__A)					:		Optional[Any]						=  box
					__A					:		Optional[Any]						=  xa - xa
					__A					:		Any						=  ya - ya
					self.ax.add_patch(
					    mpl.patches.Rectangle(
					        (xa, ya)      ,		_snake_case      ,		_snake_case      ,		fill=_snake_case      ,		edgecolor=_snake_case      ,		linewidth=self.font_size // 3      ,		alpha=self.alpha      ,		linestyle=self.linestyle      ,		)						)

	def       UpperCamelCase__(					self      ,		__lowerCamelCase      ,		__lowerCamelCase=None      ,		__lowerCamelCase=None      ,		__lowerCamelCase=None      ,		__lowerCamelCase=None						):



					'''simple docstring'''




					if len(boxes.shape						) > 2:
									__A					:		Optional[int]						=  boxes[0]
					if len(obj_ids.shape						) > 1:
									__A					:		Tuple						=  obj_ids[0]
					if len(obj_scores.shape						) > 1:
									__A					:		Any						=  obj_scores[0]
					if len(attr_ids.shape						) > 1:
									__A					:		str						=  attr_ids[0]
					if len(attr_scores.shape						) > 1:
									__A					:		Dict						=  attr_scores[0]
					if isinstance(_snake_case      ,		torch.Tensor						):
									__A					:		str						=  boxes.numpy()
					if isinstance(_snake_case      ,		_snake_case						):
									__A					:		Dict						=  np.array(_snake_case						)
					assert isinstance(_snake_case      ,		np.ndarray						)
					__A					:		Optional[int]						=  np.prod(boxes[:, 2:] - boxes[:, :2]      ,		axis=1						)
					__A					:		str						=  np.argsort(-areas						).tolist()
					__A					:		Tuple						=  boxes[sorted_idxs] if boxes is not None else None
					__A					:		Optional[int]						=  obj_ids[sorted_idxs] if obj_ids is not None else None
					__A					:		List[Any]						=  obj_scores[sorted_idxs] if obj_scores is not None else None
					__A					:		int						=  attr_ids[sorted_idxs] if attr_ids is not None else None
					__A					:		Any						=  attr_scores[sorted_idxs] if attr_scores is not None else None

					__A					:		Dict						=  [self._random_color(maximum=1						) for _ in range(len(_snake_case						)						)]
					__A					:		Optional[Any]						=  [assigned_colors[idx] for idx in sorted_idxs]
					if obj_ids is not None:
									__A					:		str						=  self._create_text_labels_attr(_snake_case      ,		_snake_case      ,		_snake_case      ,		_snake_case						)
									for i in range(len(_snake_case						)						):
													__A					:		Optional[int]						=  assigned_colors[i]
													self.add_box(boxes[i]      ,		_snake_case						)
													self.draw_labels(labels[i]      ,		boxes[i]      ,		_snake_case						)

	def       UpperCamelCase__(					self      ,		__lowerCamelCase      ,		__lowerCamelCase      ,		__lowerCamelCase						):



					'''simple docstring'''




					__A					:		Any						=  box
					__A					:		List[Any]						=  (xa, ya)
					__A					:		Optional[Any]						=  (ya - ya) * (xa - xa)
					__A					:		List[str]						=  _SMALL_OBJ * self.scale
					if instance_area < small or ya - ya < 40 * self.scale:
									if ya >= self.height - 5:
													__A					:		Any						=  (xa, ya)
									else:
													__A					:		Union[str, Any]						=  (xa, ya)

					__A					:		str						=  (ya - ya) / np.sqrt(self.height * self.width						)
					__A					:		Any						=  self._change_color_brightness(_snake_case      ,		brightness_factor=0.7						)
					__A					:		List[Any]						=  np.clip((height_ratio - 0.0_2) / 0.0_8 + 1      ,		1.2      ,		2						)
					font_size *= 0.7_5 * self.font_size

					self.draw_text(
					    text=_snake_case      ,		position=_snake_case      ,		color=_snake_case      ,		)

	def       UpperCamelCase__(					self      ,		__lowerCamelCase      ,		__lowerCamelCase      ,		__lowerCamelCase="g"      ,		__lowerCamelCase="left"      ,		):



					'''simple docstring'''




					__A					:		List[Any]						=  0
					__A					:		Union[str, Any]						=  self.font_size
					__A					:		Optional[Any]						=  np.maximum(list(mplc.to_rgb(_snake_case						)						)      ,		0.2						)
					__A					:		Dict						=  max(0.8      ,		np.max(_snake_case						)						)
					__A					:		int						=  {
					    '''facecolor''': '''black''',
					    '''alpha''': self.alpha,
					    '''pad''': self.pad,
					    '''edgecolor''': '''none''',
					}
					__A					:		List[Any]						=  position
					self.ax.text(
					    _snake_case      ,		_snake_case      ,		_snake_case      ,		size=font_size * self.scale      ,		family='''sans-serif'''      ,		bbox=_snake_case      ,		verticalalignment='''top'''      ,		horizontalalignment=_snake_case      ,		color=_snake_case      ,		zorder=10      ,		rotation=_snake_case      ,		)

	def       UpperCamelCase__(					self      ,		__lowerCamelCase=None						):



					'''simple docstring'''




					if saveas is None:
									__A					:		List[str]						=  self.saveas
					if saveas.lower().endswith('''.jpg'''						) or saveas.lower().endswith('''.png'''						):
									cva.imwrite(
									    _snake_case      ,		self._get_buffer()[:, :, ::-1]      ,		)
					else:
									self.fig.savefig(_snake_case						)

	def       UpperCamelCase__(					self      ,		__lowerCamelCase      ,		__lowerCamelCase      ,		__lowerCamelCase      ,		__lowerCamelCase						):



					'''simple docstring'''




					__A					:		Union[str, Any]						=  [self.idaobj[i] for i in classes]
					__A					:		Optional[int]						=  [self.idaattr[i] for i in attr_classes]
					__A					:		str						=  [
					    F"""{label} {score:.2f} {attr} {attr_score:.2f}"""
					    for label, score, attr, attr_score in zip(_snake_case      ,		_snake_case      ,		_snake_case      ,		_snake_case						)
					]
					return labels

	def       UpperCamelCase__(					self      ,		__lowerCamelCase      ,		__lowerCamelCase						):



					'''simple docstring'''




					__A					:		List[str]						=  [self.idaobj[i] for i in classes]
					if scores is not None:
									if labels is None:
													__A					:		Optional[int]						=  ['''{:.0f}%'''.format(s * 100						) for s in scores]
									else:
													__A					:		str						=  ['''{} {:.0f}%'''.format(_snake_case      ,		s * 100						) for li, s in zip(_snake_case      ,		_snake_case						)]
					return labels

	def       UpperCamelCase__(					self      ,		__lowerCamelCase=255						):



					'''simple docstring'''




					__A					:		Union[str, Any]						=  np.random.randint(0      ,		len(_COLORS						)						)
					__A					:		Optional[Any]						=  _COLORS[idx] * maximum
					if not self.rgb:
									__A					:		Dict						=  ret[::-1]
					return ret

	def       UpperCamelCase__(					self						):



					'''simple docstring'''




					if not self.pynb:
									__A					:		str						=  self.canvas.print_to_buffer()
									if (width, height) != (self.width, self.height):
													__A					:		List[str]						=  cva.resize(self.img      ,		(width, height)						)
									else:
													__A					:		Union[str, Any]						=  self.img
					else:
									__A					:		List[Any]						=  io.BytesIO()  # works for cairo backend
									self.canvas.print_rgba(_snake_case						)
									__A					:		Optional[Any]						=  self.width, self.height
									__A					:		Optional[Any]						=  buf.getvalue()
									__A					:		List[str]						=  self.img

					__A					:		str						=  np.frombuffer(_snake_case      ,		dtype='''uint8'''						)
					__A					:		Dict						=  buffer.reshape(_snake_case      ,		_snake_case      ,		4						)
					__A					:		List[Any]						=  np.split(_snake_case      ,		[3]      ,		axis=2						)

					try:
									import numexpr as ne  # fuse them with numexpr

									__A					:		List[str]						=  ne.evaluate('''img * (1 - alpha / 255.0) + rgb * (alpha / 255.0)'''						)
					except ImportError:
									__A					:		Optional[Any]						=  alpha.astype('''float32'''						) / 2_5_5.0
									__A					:		Optional[int]						=  img * (1 - alpha) + rgb * alpha

					return visualized_image.astype('''uint8'''						)







	def       UpperCamelCase__(					self      ,		__lowerCamelCase      ,		__lowerCamelCase						):



					'''simple docstring'''




					assert brightness_factor >= -1.0 and brightness_factor <= 1.0
					__A					:		List[Any]						=  mplc.to_rgb(_snake_case						)
					__A					:		Optional[Any]						=  colorsys.rgb_to_hls(*mplc.to_rgb(_snake_case						)						)
					__A					:		Optional[Any]						=  polygon_color[1] + (brightness_factor * polygon_color[1])
					__A					:		str						=  0.0 if modified_lightness < 0.0 else modified_lightness
					__A					:		Tuple						=  1.0 if modified_lightness > 1.0 else modified_lightness
					__A					:		List[str]						=  colorsys.hls_to_rgb(polygon_color[0]      ,		_snake_case      ,		polygon_color[2]						)
					return modified_color






a_				=    (
    np.array(
        [
            0.000,
            0.447,
            0.741,
            0.850,
            0.325,
            0.098,
            0.929,
            0.694,
            0.125,
            0.494,
            0.184,
            0.556,
            0.466,
            0.674,
            0.188,
            0.301,
            0.745,
            0.933,
            0.635,
            0.078,
            0.184,
            0.300,
            0.300,
            0.300,
            0.600,
            0.600,
            0.600,
            1.000,
            0.000,
            0.000,
            1.000,
            0.500,
            0.000,
            0.749,
            0.749,
            0.000,
            0.000,
            1.000,
            0.000,
            0.000,
            0.000,
            1.000,
            0.667,
            0.000,
            1.000,
            0.333,
            0.333,
            0.000,
            0.333,
            0.667,
            0.000,
            0.333,
            1.000,
            0.000,
            0.667,
            0.333,
            0.000,
            0.667,
            0.667,
            0.000,
            0.667,
            1.000,
            0.000,
            1.000,
            0.333,
            0.000,
            1.000,
            0.667,
            0.000,
            1.000,
            1.000,
            0.000,
            0.000,
            0.333,
            0.500,
            0.000,
            0.667,
            0.500,
            0.000,
            1.000,
            0.500,
            0.333,
            0.000,
            0.500,
            0.333,
            0.333,
            0.500,
            0.333,
            0.667,
            0.500,
            0.333,
            1.000,
            0.500,
            0.667,
            0.000,
            0.500,
            0.667,
            0.333,
            0.500,
            0.667,
            0.667,
            0.500,
            0.667,
            1.000,
            0.500,
            1.000,
            0.000,
            0.500,
            1.000,
            0.333,
            0.500,
            1.000,
            0.667,
            0.500,
            1.000,
            1.000,
            0.500,
            0.000,
            0.333,
            1.000,
            0.000,
            0.667,
            1.000,
            0.000,
            1.000,
            1.000,
            0.333,
            0.000,
            1.000,
            0.333,
            0.333,
            1.000,
            0.333,
            0.667,
            1.000,
            0.333,
            1.000,
            1.000,
            0.667,
            0.000,
            1.000,
            0.667,
            0.333,
            1.000,
            0.667,
            0.667,
            1.000,
            0.667,
            1.000,
            1.000,
            1.000,
            0.000,
            1.000,
            1.000,
            0.333,
            1.000,
            1.000,
            0.667,
            1.000,
            0.333,
            0.000,
            0.000,
            0.500,
            0.000,
            0.000,
            0.667,
            0.000,
            0.000,
            0.833,
            0.000,
            0.000,
            1.000,
            0.000,
            0.000,
            0.000,
            0.167,
            0.000,
            0.000,
            0.333,
            0.000,
            0.000,
            0.500,
            0.000,
            0.000,
            0.667,
            0.000,
            0.000,
            0.833,
            0.000,
            0.000,
            1.000,
            0.000,
            0.000,
            0.000,
            0.167,
            0.000,
            0.000,
            0.333,
            0.000,
            0.000,
            0.500,
            0.000,
            0.000,
            0.667,
            0.000,
            0.000,
            0.833,
            0.000,
            0.000,
            1.000,
            0.000,
            0.000,
            0.000,
            0.143,
            0.143,
            0.143,
            0.857,
            0.857,
            0.857,
            1.000,
            1.000,
            1.000,
        ]
    )
    .astype(np.floataa)
    .reshape(-1, 3)
)











"""simple docstring"""



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, prepare_video_inputs


if is_torch_available():
       import torch

if is_vision_available():
       from PIL import Image

       from transformers import VideoMAEImageProcessor






class 	__snake_case      (	unittest.TestCase  ):





 """simple docstring"""


 def __init__(					self      ,		__lowerCamelCase      ,		__lowerCamelCase=7      ,		__lowerCamelCase=3      ,		__lowerCamelCase=10      ,		__lowerCamelCase=18      ,		__lowerCamelCase=30      ,		__lowerCamelCase=400      ,		__lowerCamelCase=True      ,		__lowerCamelCase=None      ,		__lowerCamelCase=True      ,		__lowerCamelCase=[0.5, 0.5, 0.5]      ,		__lowerCamelCase=[0.5, 0.5, 0.5]      ,		__lowerCamelCase=None      ,		):



     '''simple docstring'''




     __A					:		Optional[Any]						=  size if size is not None else {'''shortest_edge''': 18}
     __A					:		Optional[int]						=  crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}

     __A					:		Any						=  parent
     __A					:		Union[str, Any]						=  batch_size
     __A					:		Optional[int]						=  num_channels
     __A					:		int						=  num_frames
     __A					:		Optional[int]						=  image_size
     __A					:		Union[str, Any]						=  min_resolution
     __A					:		int						=  max_resolution
     __A					:		Tuple						=  do_resize
     __A					:		str						=  size
     __A					:		Any						=  do_normalize
     __A					:		Union[str, Any]						=  image_mean
     __A					:		List[str]						=  image_std
     __A					:		Union[str, Any]						=  crop_size







 def       UpperCamelCase__(					self						):



     '''simple docstring'''




     return {
         "image_mean": self.image_mean,
         "image_std": self.image_std,
         "do_normalize": self.do_normalize,
         "do_resize": self.do_resize,
         "size": self.size,
         "crop_size": self.crop_size,
     }






@require_torch
@require_vision
class 	__snake_case      (	SCREAMING_SNAKE_CASE__							,							unittest.TestCase  ):





 """simple docstring"""


 _lowerCamelCase				 =  VideoMAEImageProcessor if is_vision_available() else None

 def       UpperCamelCase__(					self						):



     '''simple docstring'''




     __A					:		List[str]						=  VideoMAEImageProcessingTester(self						)

 @property
 def       UpperCamelCase__(					self						):



     '''simple docstring'''




     return self.image_processor_tester.prepare_image_processor_dict()

 def       UpperCamelCase__(					self						):



     '''simple docstring'''




     __A					:		Dict						=  self.image_processing_class(**self.image_processor_dict						)
     self.assertTrue(hasattr(__lowerCamelCase      ,		'''image_mean'''						)						)
     self.assertTrue(hasattr(__lowerCamelCase      ,		'''image_std'''						)						)
     self.assertTrue(hasattr(__lowerCamelCase      ,		'''do_normalize'''						)						)
     self.assertTrue(hasattr(__lowerCamelCase      ,		'''do_resize'''						)						)
     self.assertTrue(hasattr(__lowerCamelCase      ,		'''do_center_crop'''						)						)
     self.assertTrue(hasattr(__lowerCamelCase      ,		'''size'''						)						)

 def       UpperCamelCase__(					self						):



     '''simple docstring'''




     __A					:		Optional[int]						=  self.image_processing_class.from_dict(self.image_processor_dict						)
     self.assertEqual(image_processor.size      ,		{'''shortest_edge''': 18}						)
     self.assertEqual(image_processor.crop_size      ,		{'''height''': 18, '''width''': 18}						)

     __A					:		Dict						=  self.image_processing_class.from_dict(self.image_processor_dict      ,		size=42      ,		crop_size=84						)
     self.assertEqual(image_processor.size      ,		{'''shortest_edge''': 42}						)
     self.assertEqual(image_processor.crop_size      ,		{'''height''': 84, '''width''': 84}						)

 def       UpperCamelCase__(					self						):



     '''simple docstring'''




     pass

 def       UpperCamelCase__(					self						):



     '''simple docstring'''




     __A					:		List[Any]						=  self.image_processing_class(**self.image_processor_dict						)
     # create random PIL videos
     __A					:		Optional[int]						=  prepare_video_inputs(self.image_processor_tester      ,		equal_resolution=__lowerCamelCase						)
     for video in video_inputs:
         self.assertIsInstance(__lowerCamelCase      ,		__lowerCamelCase						)
         self.assertIsInstance(video[0]      ,		Image.Image						)

     # Test not batched input
     __A					:		Any						=  image_processing(video_inputs[0]      ,		return_tensors='''pt'''						).pixel_values
     self.assertEqual(
         encoded_videos.shape      ,		(
             1,
             self.image_processor_tester.num_frames,
             self.image_processor_tester.num_channels,
             self.image_processor_tester.crop_size['''height'''],
             self.image_processor_tester.crop_size['''width'''],
         )      ,		)

     # Test batched
     __A					:		int						=  image_processing(__lowerCamelCase      ,		return_tensors='''pt'''						).pixel_values
     self.assertEqual(
         encoded_videos.shape      ,		(
             self.image_processor_tester.batch_size,
             self.image_processor_tester.num_frames,
             self.image_processor_tester.num_channels,
             self.image_processor_tester.crop_size['''height'''],
             self.image_processor_tester.crop_size['''width'''],
         )      ,		)

 def       UpperCamelCase__(					self						):



     '''simple docstring'''




     __A					:		List[Any]						=  self.image_processing_class(**self.image_processor_dict						)
     # create random numpy tensors
     __A					:		List[str]						=  prepare_video_inputs(self.image_processor_tester      ,		equal_resolution=__lowerCamelCase      ,		numpify=__lowerCamelCase						)
     for video in video_inputs:
         self.assertIsInstance(__lowerCamelCase      ,		__lowerCamelCase						)
         self.assertIsInstance(video[0]      ,		np.ndarray						)

     # Test not batched input
     __A					:		List[str]						=  image_processing(video_inputs[0]      ,		return_tensors='''pt'''						).pixel_values
     self.assertEqual(
         encoded_videos.shape      ,		(
             1,
             self.image_processor_tester.num_frames,
             self.image_processor_tester.num_channels,
             self.image_processor_tester.crop_size['''height'''],
             self.image_processor_tester.crop_size['''width'''],
         )      ,		)

     # Test batched
     __A					:		int						=  image_processing(__lowerCamelCase      ,		return_tensors='''pt'''						).pixel_values
     self.assertEqual(
         encoded_videos.shape      ,		(
             self.image_processor_tester.batch_size,
             self.image_processor_tester.num_frames,
             self.image_processor_tester.num_channels,
             self.image_processor_tester.crop_size['''height'''],
             self.image_processor_tester.crop_size['''width'''],
         )      ,		)







 def       UpperCamelCase__(					self						):



     '''simple docstring'''




     __A					:		Optional[int]						=  self.image_processing_class(**self.image_processor_dict						)
     # create random PyTorch tensors
     __A					:		int						=  prepare_video_inputs(self.image_processor_tester      ,		equal_resolution=__lowerCamelCase      ,		torchify=__lowerCamelCase						)
     for video in video_inputs:
         self.assertIsInstance(__lowerCamelCase      ,		__lowerCamelCase						)
         self.assertIsInstance(video[0]      ,		torch.Tensor						)

     # Test not batched input
     __A					:		Optional[int]						=  image_processing(video_inputs[0]      ,		return_tensors='''pt'''						).pixel_values
     self.assertEqual(
         encoded_videos.shape      ,		(
             1,
             self.image_processor_tester.num_frames,
             self.image_processor_tester.num_channels,
             self.image_processor_tester.crop_size['''height'''],
             self.image_processor_tester.crop_size['''width'''],
         )      ,		)

     # Test batched
     __A					:		str						=  image_processing(__lowerCamelCase      ,		return_tensors='''pt'''						).pixel_values
     self.assertEqual(
         encoded_videos.shape      ,		(
             self.image_processor_tester.batch_size,
             self.image_processor_tester.num_frames,
             self.image_processor_tester.num_channels,
             self.image_processor_tester.crop_size['''height'''],
             self.image_processor_tester.crop_size['''width'''],
         )      ,		)




