



'''simple docstring'''
import inspect
import unittest

from transformers import SwinaSRConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch
					from torch import nn

					from transformers import SwinaSRForImageSuperResolution, SwinaSRModel
					from transformers.models.swinasr.modeling_swinasr import SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
					from PIL import Image

					from transformers import SwinaSRImageProcessor



class _A	:





		def __init__(  self			,							__UpperCAmelCase			,							__UpperCAmelCase=13			,							__UpperCAmelCase=32			,							__UpperCAmelCase=1			,							__UpperCAmelCase=3			,							__UpperCAmelCase=16			,							__UpperCAmelCase=[1, 2, 1]			,							__UpperCAmelCase=[2, 2, 4]			,							__UpperCAmelCase=2			,							__UpperCAmelCase=2.0			,							__UpperCAmelCase=True			,							__UpperCAmelCase=0.0			,							__UpperCAmelCase=0.0			,							__UpperCAmelCase=0.1			,							__UpperCAmelCase="gelu"			,							__UpperCAmelCase=False			,							__UpperCAmelCase=True			,							__UpperCAmelCase=0.02			,							__UpperCAmelCase=1E-5			,							__UpperCAmelCase=True			,							__UpperCAmelCase=None			,							__UpperCAmelCase=False			,							__UpperCAmelCase=2			,							)							->  Union[str, Any]:

					'''simple docstring'''
					__UpperCAmelCase :   Dict    					=  parent
					__UpperCAmelCase :   Optional[Any]    					=  batch_size
					__UpperCAmelCase :   Union[str, Any]    					=  image_size
					__UpperCAmelCase :   Tuple    					=  patch_size
					__UpperCAmelCase :   int    					=  num_channels
					__UpperCAmelCase :   Any    					=  embed_dim
					__UpperCAmelCase :   int    					=  depths
					__UpperCAmelCase :   Union[str, Any]    					=  num_heads
					__UpperCAmelCase :   str    					=  window_size
					__UpperCAmelCase :   List[Any]    					=  mlp_ratio
					__UpperCAmelCase :   Dict    					=  qkv_bias
					__UpperCAmelCase :   int    					=  hidden_dropout_prob
					__UpperCAmelCase :   List[str]    					=  attention_probs_dropout_prob
					__UpperCAmelCase :   Dict    					=  drop_path_rate
					__UpperCAmelCase :   Dict    					=  hidden_act
					__UpperCAmelCase :   Dict    					=  use_absolute_embeddings
					__UpperCAmelCase :   Optional[Any]    					=  patch_norm
					__UpperCAmelCase :   Optional[int]    					=  layer_norm_eps
					__UpperCAmelCase :   Dict    					=  initializer_range
					__UpperCAmelCase :   Optional[Any]    					=  is_training
					__UpperCAmelCase :   Tuple    					=  scope
					__UpperCAmelCase :   Any    					=  use_labels
					__UpperCAmelCase :   Optional[int]    					=  upscale

					# here we set some attributes to make tests pass
					__UpperCAmelCase :   Optional[int]    					=  len(lowerCamelCase__					)
					__UpperCAmelCase :   Optional[Any]    					=  embed_dim
					__UpperCAmelCase :   List[str]    					=  (image_size // patch_size) ** 2





		def 				__A							(  self					)							->  Tuple:

					'''simple docstring'''
					__UpperCAmelCase :   int    					=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

					__UpperCAmelCase :   int    					=  None
					if self.use_labels:
								__UpperCAmelCase :   Tuple    					=  ids_tensor([self.batch_size]			,							self.type_sequence_label_size					)

					__UpperCAmelCase :   List[Any]    					=  self.get_config()

					return config, pixel_values, labels





		def 				__A							(  self					)							->  int:

					'''simple docstring'''
					return SwinaSRConfig(
					    image_size=self.image_size			,							patch_size=self.patch_size			,							num_channels=self.num_channels			,							embed_dim=self.embed_dim			,							depths=self.depths			,							num_heads=self.num_heads			,							window_size=self.window_size			,							mlp_ratio=self.mlp_ratio			,							qkv_bias=self.qkv_bias			,							hidden_dropout_prob=self.hidden_dropout_prob			,							attention_probs_dropout_prob=self.attention_probs_dropout_prob			,							drop_path_rate=self.drop_path_rate			,							hidden_act=self.hidden_act			,							use_absolute_embeddings=self.use_absolute_embeddings			,							path_norm=self.patch_norm			,							layer_norm_eps=self.layer_norm_eps			,							initializer_range=self.initializer_range			,							upscale=self.upscale			,							)





		def 				__A							(  self			,							__UpperCAmelCase			,							__UpperCAmelCase			,							__UpperCAmelCase					)							->  Dict:

					'''simple docstring'''
					__UpperCAmelCase :   Optional[int]    					=  SwinaSRModel(config=lowerCamelCase__					)
					model.to(lowerCamelCase__					)
					model.eval()
					__UpperCAmelCase :   Dict    					=  model(lowerCamelCase__					)

					self.parent.assertEqual(
					    result.last_hidden_state.shape			,							(self.batch_size, self.embed_dim, self.image_size, self.image_size)					)





		def 				__A							(  self			,							__UpperCAmelCase			,							__UpperCAmelCase			,							__UpperCAmelCase					)							->  Any:

					'''simple docstring'''
					__UpperCAmelCase :   List[Any]    					=  SwinaSRForImageSuperResolution(lowerCamelCase__					)
					model.to(lowerCamelCase__					)
					model.eval()
					__UpperCAmelCase :   List[Any]    					=  model(lowerCamelCase__					)

					__UpperCAmelCase :   Union[str, Any]    					=  self.image_size * self.upscale
					self.parent.assertEqual(
					    result.reconstruction.shape			,							(self.batch_size, self.num_channels, expected_image_size, expected_image_size)					)





		def 				__A							(  self					)							->  Tuple:

					'''simple docstring'''
					__UpperCAmelCase :   Optional[Any]    					=  self.prepare_config_and_inputs()
					__UpperCAmelCase :   Dict    					=  config_and_inputs
					__UpperCAmelCase :   Dict    					=  {'pixel_values': pixel_values}
					return config, inputs_dict



@require_torch
class _A	(     __SCREAMING_SNAKE_CASE						,					__SCREAMING_SNAKE_CASE						,					unittest.TestCase     ):
		_SCREAMING_SNAKE_CASE       :     int       =      (SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
		_SCREAMING_SNAKE_CASE       :     Tuple       =      {"""feature-extraction""": SwinaSRModel} if is_torch_available() else {}

		_SCREAMING_SNAKE_CASE       :     Optional[Any]       =      False
		_SCREAMING_SNAKE_CASE       :     Optional[Any]       =      False
		_SCREAMING_SNAKE_CASE       :     List[str]       =      False
		_SCREAMING_SNAKE_CASE       :     Optional[Any]       =      False
		_SCREAMING_SNAKE_CASE       :     Union[str, Any]       =      False





		def 				__A							(  self					)							->  Optional[Any]:

					'''simple docstring'''
					__UpperCAmelCase :   Tuple    					=  SwinaSRModelTester(self					)
					__UpperCAmelCase :   Tuple    					=  ConfigTester(self			,							config_class=lowerCamelCase__			,							embed_dim=37					)





		def 				__A							(  self					)							->  List[Any]:

					'''simple docstring'''
					self.config_tester.create_and_test_config_to_json_string()
					self.config_tester.create_and_test_config_to_json_file()
					self.config_tester.create_and_test_config_from_and_save_pretrained()
					self.config_tester.create_and_test_config_with_num_labels()
					self.config_tester.check_config_can_be_init_without_params()
					self.config_tester.check_config_arguments_init()





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

					'''simple docstring'''
					__UpperCAmelCase :   str    					=  self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*lowerCamelCase__					)





		def 				__A							(  self					)							->  int:

					'''simple docstring'''
					__UpperCAmelCase :   Optional[int]    					=  self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_super_resolution(*lowerCamelCase__					)





		@unittest.skip(reason="""Got `CUDA error: misaligned address` with PyTorch 2.0.0."""					)
		def 				__A							(  self					)							->  Optional[int]:

					'''simple docstring'''
					pass





		@unittest.skip(reason="""Swin2SR does not use inputs_embeds"""					)
		def 				__A							(  self					)							->  str:

					'''simple docstring'''
					pass





		@unittest.skip(reason="""Swin2SR does not support training yet"""					)
		def 				__A							(  self					)							->  Any:

					'''simple docstring'''
					pass





		@unittest.skip(reason="""Swin2SR does not support training yet"""					)
		def 				__A							(  self					)							->  Optional[Any]:

					'''simple docstring'''
					pass





		def 				__A							(  self					)							->  Any:

					'''simple docstring'''
					__UpperCAmelCase :   List[str]    					=  self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
								__UpperCAmelCase :   Optional[Any]    					=  model_class(lowerCamelCase__					)
								self.assertIsInstance(model.get_input_embeddings()			,							(nn.Module)					)
								__UpperCAmelCase :   str    					=  model.get_output_embeddings()
								self.assertTrue(x is None or isinstance(lowerCamelCase__			,							nn.Linear					)					)





		def 				__A							(  self					)							->  List[str]:

					'''simple docstring'''
					__UpperCAmelCase :   Optional[Any]    					=  self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
								__UpperCAmelCase :   Optional[int]    					=  model_class(lowerCamelCase__					)
								__UpperCAmelCase :   Any    					=  inspect.signature(model.forward					)
								# signature.parameters is an OrderedDict => so arg_names order is deterministic
								__UpperCAmelCase :   int    					=  [*signature.parameters.keys()]

								__UpperCAmelCase :   Tuple    					=  ['pixel_values']
								self.assertListEqual(arg_names[:1]			,							lowerCamelCase__					)





		@slow
		def 				__A							(  self					)							->  List[str]:

					'''simple docstring'''

					for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
								__UpperCAmelCase :   Dict    					=  SwinaSRModel.from_pretrained(lowerCamelCase__					)
								self.assertIsNotNone(lowerCamelCase__					)





		def 				__A							(  self					)							->  str:

					'''simple docstring'''
					__UpperCAmelCase :   Optional[int]    					=  self.model_tester.prepare_config_and_inputs_for_common()

					__UpperCAmelCase :   Optional[int]    					=  _config_zero_init(lowerCamelCase__					)
					for model_class in self.all_model_classes:
								__UpperCAmelCase :   Optional[Any]    					=  model_class(config=lowerCamelCase__					)
								for name, param in model.named_parameters():
											if "logit_scale" in name:
														continue
											if param.requires_grad:
														self.assertIn(
														    ((param.data.mean() * 1E9).round() / 1E9).item()			,							[0.0, 1.0]			,							msg=f'Parameter {name} of model {model_class} seems not properly initialized'			,							)





		def 				__A							(  self					)							->  int:

					'''simple docstring'''
					__UpperCAmelCase :   int    					=  self.model_tester.prepare_config_and_inputs_for_common()
					__UpperCAmelCase :   Any    					=  True

					for model_class in self.all_model_classes:
								__UpperCAmelCase :   Tuple    					=  True
								__UpperCAmelCase :   List[Any]    					=  False
								__UpperCAmelCase :   int    					=  True
								__UpperCAmelCase :   Optional[Any]    					=  model_class(lowerCamelCase__					)
								model.to(lowerCamelCase__					)
								model.eval()
								with torch.no_grad():
											__UpperCAmelCase :   int    					=  model(**self._prepare_for_class(lowerCamelCase__			,							lowerCamelCase__					)					)
								__UpperCAmelCase :   str    					=  outputs.attentions
								__UpperCAmelCase :   Union[str, Any]    					=  len(self.model_tester.depths					)
								self.assertEqual(len(lowerCamelCase__					)			,							lowerCamelCase__					)

								# check that output_attentions also work using config
								del inputs_dict["output_attentions"]
								__UpperCAmelCase :   Optional[Any]    					=  True
								__UpperCAmelCase :   Any    					=  config.window_size**2
								__UpperCAmelCase :   Optional[int]    					=  model_class(lowerCamelCase__					)
								model.to(lowerCamelCase__					)
								model.eval()
								with torch.no_grad():
											__UpperCAmelCase :   List[str]    					=  model(**self._prepare_for_class(lowerCamelCase__			,							lowerCamelCase__					)					)
								__UpperCAmelCase :   str    					=  outputs.attentions
								self.assertEqual(len(lowerCamelCase__					)			,							lowerCamelCase__					)

								self.assertListEqual(
								    list(attentions[0].shape[-3:]					)			,							[self.model_tester.num_heads[0], window_size_squared, window_size_squared]			,							)
								__UpperCAmelCase :   Tuple    					=  len(lowerCamelCase__					)

								# Check attention is always last and order is fine
								__UpperCAmelCase :   Union[str, Any]    					=  True
								__UpperCAmelCase :   int    					=  True
								__UpperCAmelCase :   int    					=  model_class(lowerCamelCase__					)
								model.to(lowerCamelCase__					)
								model.eval()
								with torch.no_grad():
											__UpperCAmelCase :   Any    					=  model(**self._prepare_for_class(lowerCamelCase__			,							lowerCamelCase__					)					)

								self.assertEqual(out_len + 1			,							len(lowerCamelCase__					)					)

								__UpperCAmelCase :   int    					=  outputs.attentions

								self.assertEqual(len(lowerCamelCase__					)			,							lowerCamelCase__					)

								self.assertListEqual(
								    list(self_attentions[0].shape[-3:]					)			,							[self.model_tester.num_heads[0], window_size_squared, window_size_squared]			,							)



@require_vision
@require_torch
@slow
class _A	(     unittest.TestCase     ):





		def 				__A							(  self					)							->  Optional[int]:

					'''simple docstring'''
					__UpperCAmelCase :   Optional[int]    					=  SwinaSRImageProcessor()
					__UpperCAmelCase :   Optional[int]    					=  SwinaSRForImageSuperResolution.from_pretrained("""caidas/swin2SR-classical-sr-x2-64"""					).to(lowerCamelCase__					)

					__UpperCAmelCase :   Union[str, Any]    					=  Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""					)
					__UpperCAmelCase :   Optional[int]    					=  processor(images=lowerCamelCase__			,							return_tensors="""pt"""					).to(lowerCamelCase__					)

					# forward pass
					with torch.no_grad():
								__UpperCAmelCase :   int    					=  model(**lowerCamelCase__					)

					# verify the logits
					__UpperCAmelCase :   Union[str, Any]    					=  torch.Size([1, 3, 976, 1_296]					)
					self.assertEqual(outputs.reconstruction.shape			,							lowerCamelCase__					)
					__UpperCAmelCase :   str    					=  torch.tensor(
					    [[0.5458, 0.5546, 0.5638], [0.5526, 0.5565, 0.5651], [0.5396, 0.5426, 0.5621]]					).to(lowerCamelCase__					)
					self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3]			,							lowerCamelCase__			,							atol=1E-4					)					)












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_			:Tuple	    =		1000




class 							__A	:





				"""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(lowerCamelCase__				,    torch.Tensor       ):
														__UpperCamelCase :   Union[str, Any]									=img.numpy().astype('np.uint8'       )
									if isinstance(lowerCamelCase__				,    lowerCamelCase__       ):
														__UpperCamelCase :   List[str]									=img_tensorize(lowerCamelCase__       )
									assert isinstance(lowerCamelCase__				,    np.ndarray       )

									__UpperCamelCase						,							__UpperCamelCase :   Any									=img.shape[1], img.shape[0]
									__UpperCamelCase :   Any									=mplfigure.Figure(frameon=lowerCamelCase__       )
									__UpperCamelCase :   Any									=fig.get_dpi()
									__UpperCamelCase :   Optional[Any]									=(width * scale + 1E-2) / dpi
									__UpperCamelCase :   Optional[Any]									=(height * scale + 1E-2) / dpi
									fig.set_size_inches(lowerCamelCase__				,    lowerCamelCase__       )
									__UpperCamelCase :   Dict									=fig.add_axes([0.0, 0.0, 1.0, 1.0]       )
									ax.axis('off'       )
									ax.set_xlim(0.0				,    lowerCamelCase__       )
									ax.set_ylim(lowerCamelCase__       )

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


				def  __lowercase				(					self				,    lowerCamelCase__				,    lowerCamelCase__=None       ):




									"""simple docstring"""

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


				def  __lowercase				(					self				,    lowerCamelCase__				,    lowerCamelCase__=None				,    lowerCamelCase__=None				,    lowerCamelCase__=None				,    lowerCamelCase__=None       ):




									"""simple docstring"""

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

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


				def  __lowercase				(					self				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__       ):




									"""simple docstring"""

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

									__UpperCamelCase :   Tuple									=(ya - ya) / np.sqrt(self.height * self.width       )
									__UpperCamelCase :   List[Any]									=self._change_color_brightness(lowerCamelCase__				,    brightness_factor=0.7       )
									__UpperCamelCase :   Any									=np.clip((height_ratio - 0.02) / 0.08 + 1				,    1.2				,    2       )
									font_size *= 0.75 * self.font_size

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


				def  __lowercase				(					self				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__="g"				,    lowerCamelCase__="left"				,    ):




									"""simple docstring"""

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


				def  __lowercase				(					self				,    lowerCamelCase__=None       ):




									"""simple docstring"""

									if saveas is None:
														__UpperCamelCase :   Optional[int]									=self.saveas
									if saveas.lower().endswith('.jpg'       ) or saveas.lower().endswith('.png'       ):
														cva.imwrite(
														    lowerCamelCase__				,    self._get_buffer()[:, :, ::-1]				,    )
									else:
														self.fig.savefig(lowerCamelCase__       )


				def  __lowercase				(					self				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__       ):




									"""simple docstring"""

									__UpperCamelCase :   Optional[int]									=[self.idaobj[i] for i in classes]
									__UpperCamelCase :   str									=[self.idaattr[i] for i in attr_classes]
									__UpperCamelCase :   Any									=[
									    f'{label} {score:.2f} {attr} {attr_score:.2f}'
									    for label, score, attr, attr_score in zip(lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__       )
									]
									return labels


				def  __lowercase				(					self				,    lowerCamelCase__				,    lowerCamelCase__       ):




									"""simple docstring"""

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


				def  __lowercase				(					self				,    lowerCamelCase__=255       ):




									"""simple docstring"""

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


				def  __lowercase				(					self       ):




									"""simple docstring"""

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

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

									try:
														import numexpr as ne  # fuse them with numexpr

														__UpperCamelCase :   List[Any]									=ne.evaluate('img * (1 - alpha / 255.0) + rgb * (alpha / 255.0)'       )
									except ImportError:
														__UpperCamelCase :   int									=alpha.astype('float32'       ) / 255.0
														__UpperCamelCase :   Tuple									=img * (1 - alpha) + rgb * alpha

									return visualized_image.astype('uint8'       )







				def  __lowercase				(					self				,    lowerCamelCase__				,    lowerCamelCase__       ):




									"""simple docstring"""

									assert brightness_factor >= -1.0 and brightness_factor <= 1.0
									__UpperCamelCase :   List[Any]									=mplc.to_rgb(lowerCamelCase__       )
									__UpperCamelCase :   Dict									=colorsys.rgb_to_hls(*mplc.to_rgb(lowerCamelCase__       )       )
									__UpperCamelCase :   Dict									=polygon_color[1] + (brightness_factor * polygon_color[1])
									__UpperCamelCase :   Tuple									=0.0 if modified_lightness < 0.0 else modified_lightness
									__UpperCamelCase :   str									=1.0 if modified_lightness > 1.0 else modified_lightness
									__UpperCamelCase :   Union[str, Any]									=colorsys.hls_to_rgb(polygon_color[0]				,    lowerCamelCase__				,    polygon_color[2]       )
									return modified_color
A_			:Union[str, Any]	    =		(
    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)
)

