



"""simple docstring"""
import os
import tempfile
import unittest

import numpy as np
import torch

from diffusers.models import ModelMixin, UNetaDConditionModel
from diffusers.models.attention_processor import AttnProcessor, LoRAAttnProcessor
from diffusers.utils import (
    floats_tensor,
    logging,
    skip_mps,
    torch_device,
)
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import enable_full_determinism

from .test_modeling_common import ModelTesterMixin, UNetTesterMixin


enable_full_determinism()

__a           =							logging.get_logger(__name__)
def   A_    (     _lowercase,   _lowercase = True      ):







						'''simple docstring'''


						snake_case_					:str		=     {}
						for name in model.attn_processors.keys():
												snake_case_					:Dict		=     name.endswith("""attn2.processor"""      ) and not (
												    name.startswith("""transformer_in"""      ) or """temp_attentions""" in name.split("""."""      )
												)
												snake_case_					:Union[str, Any]		=     model.config.cross_attention_dim if has_cross_attention else None
												if name.startswith("""mid_block"""      ):
																		snake_case_					:Optional[Any]		=     model.config.block_out_channels[-1]
												elif name.startswith("""up_blocks"""      ):
																		snake_case_					:int		=     int(name[len("""up_blocks."""      )]      )
																		snake_case_					:int		=     list(reversed(model.config.block_out_channels      )      )[block_id]
												elif name.startswith("""down_blocks"""      ):
																		snake_case_					:Tuple		=     int(name[len("""down_blocks."""      )]      )
																		snake_case_					:str		=     model.config.block_out_channels[block_id]
												elif name.startswith("""transformer_in"""      ):
																		# Note that the `8 * ...` comes from: https://github.com/huggingface/diffusers/blob/7139f0e874f10b2463caa8cbd585762a309d12d6/src/diffusers/models/unet_3d_condition.py#L148
																		snake_case_					:List[Any]		=     8 * model.config.attention_head_dim

												snake_case_					:Union[str, Any]		=     LoRAAttnProcessor(hidden_size=_lowercase,   cross_attention_dim=_lowercase      )
												snake_case_					:Union[str, Any]		=     lora_attn_procs[name].to(model.device      )

												if mock_weights:
																		# add 1 to weights to mock trained weights
																		with torch.no_grad():
																								lora_attn_procs[name].to_q_lora.up.weight += 1
																								lora_attn_procs[name].to_k_lora.up.weight += 1
																								lora_attn_procs[name].to_v_lora.up.weight += 1
																								lora_attn_procs[name].to_out_lora.up.weight += 1

						return lora_attn_procs

@skip_mps
class 							lowerCamelCase    (     _lowerCAmelCase       ,		_lowerCAmelCase       ,		unittest.TestCase							):






					'''simple docstring'''





					_A						:     Optional[Any]		=	UNetaDConditionModel
					_A						:     Any		=	"""sample"""






					@property
					def   lowerCAmelCase_							(			self:				List[Any]		)  ->      Optional[Any]:
											snake_case_					:Optional[int]		=     4
											snake_case_					:str		=     4
											snake_case_					:List[str]		=     4
											snake_case_					:Any		=     (32, 32)

											snake_case_					:Dict		=     floats_tensor((batch_size, num_channels, num_frames) + sizes		).to(snake_case		)
											snake_case_					:Union[str, Any]		=     torch.tensor([10]		).to(snake_case		)
											snake_case_					:List[Any]		=     floats_tensor((batch_size, 4, 32)		).to(snake_case		)

											return {"sample": noise, "timestep": time_step, "encoder_hidden_states": encoder_hidden_states}






					@property
					def   lowerCAmelCase_							(			self:				List[str]		)  ->      int:
											return (4, 4, 32, 32)






					@property
					def   lowerCAmelCase_							(			self:				int		)  ->      List[str]:
											return (4, 4, 32, 32)






					def   lowerCAmelCase_							(			self:				Optional[int]		)  ->      List[str]:
											snake_case_					:Union[str, Any]		=     {
											    """block_out_channels""": (32, 64),
											    """down_block_types""": (
											        """CrossAttnDownBlock3D""",
											        """DownBlock3D""",
											    ),
											    """up_block_types""": ("""UpBlock3D""", """CrossAttnUpBlock3D"""),
											    """cross_attention_dim""": 32,
											    """attention_head_dim""": 8,
											    """out_channels""": 4,
											    """in_channels""": 4,
											    """layers_per_block""": 1,
											    """sample_size""": 32,
											}
											snake_case_					:List[str]		=     self.dummy_input
											return init_dict, inputs_dict






					@unittest.skipIf(
					    torch_device != """cuda""" or not is_xformers_available()		,	reason="""XFormers attention is only available with CUDA and `xformers` installed"""		,	)
					def   lowerCAmelCase_							(			self:				Union[str, Any]		)  ->      List[str]:
											snake_case_,			snake_case_					:Any		=     self.prepare_init_args_and_inputs_for_common()
											snake_case_					:Dict		=     self.model_class(**snake_case		)

											model.enable_xformers_memory_efficient_attention()

											assert (
											    model.mid_block.attentions[0].transformer_blocks[0].attna.processor.__class__.__name__
											    == "XFormersAttnProcessor"
											), "xformers is not enabled"






					def   lowerCAmelCase_							(			self:				Union[str, Any]		)  ->      Tuple:
											snake_case_,			snake_case_					:List[str]		=     self.prepare_init_args_and_inputs_for_common()

											snake_case_					:Dict		=     32

											snake_case_					:Tuple		=     self.model_class(**snake_case		)
											model.to(snake_case		)
											model.eval()

											with torch.no_grad():
																	snake_case_					:List[Any]		=     model(**snake_case		)

																	if isinstance(snake_case		,	snake_case		):
																							snake_case_					:Optional[int]		=     output.sample

											self.assertIsNotNone(snake_case		)
											snake_case_					:Tuple		=     inputs_dict["""sample"""].shape
											self.assertEqual(output.shape		,	snake_case		,	"""Input and output shapes do not match"""		)






					def   lowerCAmelCase_							(			self:				Dict		)  ->      Optional[Any]:
											snake_case_,			snake_case_					:str		=     self.prepare_init_args_and_inputs_for_common()
											snake_case_					:Any		=     self.model_class(**snake_case		)
											model.to(snake_case		)
											model.eval()

											with torch.no_grad():
																	# Warmup pass when using mps (see #372)
																	if torch_device == "mps" and isinstance(snake_case		,	snake_case		):
																							model(**self.dummy_input		)

																	snake_case_					:Dict		=     model(**snake_case		)
																	if isinstance(snake_case		,	snake_case		):
																							snake_case_					:Optional[Any]		=     first.sample

																	snake_case_					:int		=     model(**snake_case		)
																	if isinstance(snake_case		,	snake_case		):
																							snake_case_					:Optional[Any]		=     second.sample

											snake_case_					:str		=     first.cpu().numpy()
											snake_case_					:str		=     second.cpu().numpy()
											snake_case_					:Optional[int]		=     out_a[~np.isnan(snake_case		)]
											snake_case_					:int		=     out_a[~np.isnan(snake_case		)]
											snake_case_					:int		=     np.amax(np.abs(out_a - out_a		)		)
											self.assertLessEqual(snake_case		,	1E-5		)






					def   lowerCAmelCase_							(			self:				str		)  ->      int:
											snake_case_,			snake_case_					:str		=     self.prepare_init_args_and_inputs_for_common()

											snake_case_					:Union[str, Any]		=     8

											snake_case_					:Optional[int]		=     self.model_class(**snake_case		)
											model.to(snake_case		)
											model.eval()

											model.set_attention_slice("""auto"""		)
											with torch.no_grad():
																	snake_case_					:Optional[Any]		=     model(**snake_case		)
											assert output is not None

											model.set_attention_slice("""max"""		)
											with torch.no_grad():
																	snake_case_					:List[Any]		=     model(**snake_case		)
											assert output is not None

											model.set_attention_slice(2		)
											with torch.no_grad():
																	snake_case_					:List[Any]		=     model(**snake_case		)
											assert output is not None






					def   lowerCAmelCase_							(			self:				Optional[Any]		)  ->      Optional[Any]:
											snake_case_,			snake_case_					:Optional[Any]		=     self.prepare_init_args_and_inputs_for_common()

											snake_case_					:List[str]		=     8

											snake_case_					:List[Any]		=     self.model_class(**snake_case		)
											model.to(snake_case		)

											with torch.no_grad():
																	snake_case_					:Any		=     model(**snake_case		).sample

											snake_case_					:Optional[Any]		=     create_lora_layers(snake_case		)

											# make sure we can set a list of attention processors
											model.set_attn_processor(snake_case		)
											model.to(snake_case		)

											# test that attn processors can be set to itself
											model.set_attn_processor(model.attn_processors		)

											with torch.no_grad():
																	snake_case_					:List[str]		=     model(**snake_case		,	cross_attention_kwargs={"""scale""": 0.0}		).sample
																	snake_case_					:List[Any]		=     model(**snake_case		,	cross_attention_kwargs={"""scale""": 0.5}		).sample
																	snake_case_					:Union[str, Any]		=     model(**snake_case		,	cross_attention_kwargs={"""scale""": 0.5}		).sample

											assert (samplea - samplea).abs().max() < 3E-3
											assert (samplea - samplea).abs().max() < 3E-3

											# sample 2 and sample 3 should be different
											assert (samplea - samplea).abs().max() > 3E-3






					def   lowerCAmelCase_							(			self:				List[Any]		)  ->      Optional[Any]:
											snake_case_,			snake_case_					:Optional[int]		=     self.prepare_init_args_and_inputs_for_common()

											snake_case_					:Union[str, Any]		=     8

											torch.manual_seed(0		)
											snake_case_					:Optional[int]		=     self.model_class(**snake_case		)
											model.to(snake_case		)

											with torch.no_grad():
																	snake_case_					:Optional[Any]		=     model(**snake_case		).sample

											snake_case_					:List[str]		=     create_lora_layers(snake_case		)
											model.set_attn_processor(snake_case		)

											with torch.no_grad():
																	snake_case_					:List[Any]		=     model(**snake_case		,	cross_attention_kwargs={"""scale""": 0.5}		).sample

											with tempfile.TemporaryDirectory() as tmpdirname:
																	model.save_attn_procs(snake_case		)
																	self.assertTrue(os.path.isfile(os.path.join(snake_case		,	"""pytorch_lora_weights.bin"""		)		)		)
																	torch.manual_seed(0		)
																	snake_case_					:List[Any]		=     self.model_class(**snake_case		)
																	new_model.to(snake_case		)
																	new_model.load_attn_procs(snake_case		)

											with torch.no_grad():
																	snake_case_					:Optional[Any]		=     new_model(**snake_case		,	cross_attention_kwargs={"""scale""": 0.5}		).sample

											assert (sample - new_sample).abs().max() < 1E-3

											# LoRA and no LoRA should NOT be the same
											assert (sample - old_sample).abs().max() > 1E-4






					def   lowerCAmelCase_							(			self:				str		)  ->      Union[str, Any]:
											snake_case_,			snake_case_					:List[str]		=     self.prepare_init_args_and_inputs_for_common()

											snake_case_					:Tuple		=     8

											torch.manual_seed(0		)
											snake_case_					:List[str]		=     self.model_class(**snake_case		)
											model.to(snake_case		)

											with torch.no_grad():
																	snake_case_					:Optional[Any]		=     model(**snake_case		).sample

											snake_case_					:str		=     create_lora_layers(snake_case		)
											model.set_attn_processor(snake_case		)

											with torch.no_grad():
																	snake_case_					:Optional[int]		=     model(**snake_case		,	cross_attention_kwargs={"""scale""": 0.5}		).sample

											with tempfile.TemporaryDirectory() as tmpdirname:
																	model.save_attn_procs(snake_case		,	safe_serialization=snake_case		)
																	self.assertTrue(os.path.isfile(os.path.join(snake_case		,	"""pytorch_lora_weights.safetensors"""		)		)		)
																	torch.manual_seed(0		)
																	snake_case_					:Any		=     self.model_class(**snake_case		)
																	new_model.to(snake_case		)
																	new_model.load_attn_procs(snake_case		)

											with torch.no_grad():
																	snake_case_					:Optional[int]		=     new_model(**snake_case		,	cross_attention_kwargs={"""scale""": 0.5}		).sample

											assert (sample - new_sample).abs().max() < 3E-3

											# LoRA and no LoRA should NOT be the same
											assert (sample - old_sample).abs().max() > 1E-4






					def   lowerCAmelCase_							(			self:				Dict		)  ->      Optional[Any]:
											# enable deterministic behavior for gradient checkpointing
											snake_case_,			snake_case_					:Union[str, Any]		=     self.prepare_init_args_and_inputs_for_common()

											snake_case_					:Any		=     8

											torch.manual_seed(0		)
											snake_case_					:int		=     self.model_class(**snake_case		)
											model.to(snake_case		)

											snake_case_					:List[Any]		=     create_lora_layers(snake_case		,	mock_weights=snake_case		)
											model.set_attn_processor(snake_case		)
											# Saving as torch, properly reloads with directly filename
											with tempfile.TemporaryDirectory() as tmpdirname:
																	model.save_attn_procs(snake_case		)
																	self.assertTrue(os.path.isfile(os.path.join(snake_case		,	"""pytorch_lora_weights.bin"""		)		)		)
																	torch.manual_seed(0		)
																	snake_case_					:Union[str, Any]		=     self.model_class(**snake_case		)
																	new_model.to(snake_case		)
																	new_model.load_attn_procs(snake_case		,	weight_name="""pytorch_lora_weights.bin"""		)






					def   lowerCAmelCase_							(			self:				List[str]		)  ->      Tuple:
											snake_case_,			snake_case_					:Union[str, Any]		=     self.prepare_init_args_and_inputs_for_common()

											snake_case_					:Dict		=     8

											torch.manual_seed(0		)
											snake_case_					:Dict		=     self.model_class(**snake_case		)
											model.to(snake_case		)

											snake_case_					:Union[str, Any]		=     create_lora_layers(snake_case		,	mock_weights=snake_case		)
											model.set_attn_processor(snake_case		)
											# Saving as torch, properly reloads with directly filename
											with tempfile.TemporaryDirectory() as tmpdirname:
																	model.save_attn_procs(snake_case		)
																	self.assertTrue(os.path.isfile(os.path.join(snake_case		,	"""pytorch_lora_weights.bin"""		)		)		)
																	torch.manual_seed(0		)
																	snake_case_					:Optional[int]		=     self.model_class(**snake_case		)
																	new_model.to(snake_case		)
																	with self.assertRaises(snake_case		) as e:
																							new_model.load_attn_procs(snake_case		,	use_safetensors=snake_case		)
																	self.assertIn("""Error no file named pytorch_lora_weights.safetensors"""		,	str(e.exception		)		)






					def   lowerCAmelCase_							(			self:				Dict		)  ->      Dict:
											snake_case_,			snake_case_					:str		=     self.prepare_init_args_and_inputs_for_common()

											snake_case_					:int		=     8

											torch.manual_seed(0		)
											snake_case_					:List[Any]		=     self.model_class(**snake_case		)
											model.to(snake_case		)

											with torch.no_grad():
																	snake_case_					:List[str]		=     model(**snake_case		).sample

											snake_case_					:Optional[Any]		=     create_lora_layers(snake_case		)
											model.set_attn_processor(snake_case		)

											with torch.no_grad():
																	snake_case_					:List[Any]		=     model(**snake_case		,	cross_attention_kwargs={"""scale""": 0.0}		).sample

											model.set_attn_processor(AttnProcessor()		)

											with torch.no_grad():
																	snake_case_					:Dict		=     model(**snake_case		).sample

											assert (sample - new_sample).abs().max() < 1E-4
											assert (sample - old_sample).abs().max() < 3E-3






					@unittest.skipIf(
					    torch_device != """cuda""" or not is_xformers_available()		,	reason="""XFormers attention is only available with CUDA and `xformers` installed"""		,	)
					def   lowerCAmelCase_							(			self:				Any		)  ->      Union[str, Any]:
											# enable deterministic behavior for gradient checkpointing
											snake_case_,			snake_case_					:Optional[int]		=     self.prepare_init_args_and_inputs_for_common()

											snake_case_					:Optional[Any]		=     4

											torch.manual_seed(0		)
											snake_case_					:Dict		=     self.model_class(**snake_case		)
											model.to(snake_case		)
											snake_case_					:int		=     create_lora_layers(snake_case		)
											model.set_attn_processor(snake_case		)

											# default
											with torch.no_grad():
																	snake_case_					:Union[str, Any]		=     model(**snake_case		).sample

																	model.enable_xformers_memory_efficient_attention()
																	snake_case_					:Optional[int]		=     model(**snake_case		).sample

																	model.disable_xformers_memory_efficient_attention()
																	snake_case_					:int		=     model(**snake_case		).sample

											assert (sample - on_sample).abs().max() < 1E-4
											assert (sample - off_sample).abs().max() < 1E-4






					def   lowerCAmelCase_							(			self:				List[Any]		)  ->      str:
											snake_case_,			snake_case_					:List[Any]		=     self.prepare_init_args_and_inputs_for_common()
											snake_case_					:Dict		=     32

											snake_case_					:Any		=     self.model_class(**snake_case		)
											model.to(snake_case		)
											model.eval()

											with torch.no_grad():
																	snake_case_					:Dict		=     model(**snake_case		)[0]

											model.enable_forward_chunking()
											with torch.no_grad():
																	snake_case_					:Optional[Any]		=     model(**snake_case		)[0]

											self.assertEqual(output.shape		,	output_a.shape		,	"""Shape doesn't match"""		)
											assert np.abs(output.cpu() - output_a.cpu()		).max() < 1E-2


# (todo: sayakpaul) implement SLOW tests.





"""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           =							10_00
class 							lowerCamelCase    :






					'''simple docstring'''





					def __init__(			self:				Dict		,	snake_case:				List[str]		,	snake_case:				Optional[int]=1.2		,	snake_case:				List[Any]="g"		,	snake_case:				Dict=0.5		,	snake_case:				Dict="-"		,	snake_case:				Tuple="test_out.jpg"		,	snake_case:				List[str]=True		,	snake_case:				List[Any]=False		,	snake_case:				List[str]=None		,	snake_case:				int=None		,	snake_case:				Tuple=0.7		,	)  ->      Optional[int]:
											if isinstance(snake_case		,	torch.Tensor		):
																	snake_case_					:Union[str, Any]		=     img.numpy().astype("""np.uint8"""		)
											if isinstance(snake_case		,	snake_case		):
																	snake_case_					:Optional[Any]		=     img_tensorize(snake_case		)
											assert isinstance(snake_case		,	np.ndarray		)

											snake_case_,			snake_case_					:Dict		=     img.shape[1], img.shape[0]
											snake_case_					:List[Any]		=     mplfigure.Figure(frameon=snake_case		)
											snake_case_					:Any		=     fig.get_dpi()
											snake_case_					:Tuple		=     (width * scale + 1E-2) / dpi
											snake_case_					:Any		=     (height * scale + 1E-2) / dpi
											fig.set_size_inches(snake_case		,	snake_case		)
											snake_case_					:str		=     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		)

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






					def   lowerCAmelCase_							(			self:				int		,	snake_case:				Dict		,	snake_case:				Any=None		)  ->      List[str]:
											if color is None:
																	snake_case_					:Any		=     self.edgecolor
											((snake_case_),			(snake_case_),			(snake_case_),			(snake_case_))					:List[Any]		=     box
											snake_case_					:Union[str, Any]		=     xa - xa
											snake_case_					:Dict		=     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   lowerCAmelCase_							(			self:				Dict		,	snake_case:				Union[str, Any]		,	snake_case:				Union[str, Any]=None		,	snake_case:				Any=None		,	snake_case:				List[str]=None		,	snake_case:				int=None		)  ->      Any:
											if len(boxes.shape		) > 2:
																	snake_case_					:str		=     boxes[0]
											if len(obj_ids.shape		) > 1:
																	snake_case_					:Optional[int]		=     obj_ids[0]
											if len(obj_scores.shape		) > 1:
																	snake_case_					:Union[str, Any]		=     obj_scores[0]
											if len(attr_ids.shape		) > 1:
																	snake_case_					:Union[str, Any]		=     attr_ids[0]
											if len(attr_scores.shape		) > 1:
																	snake_case_					:Optional[int]		=     attr_scores[0]
											if isinstance(snake_case		,	torch.Tensor		):
																	snake_case_					:str		=     boxes.numpy()
											if isinstance(snake_case		,	snake_case		):
																	snake_case_					:List[str]		=     np.array(snake_case		)
											assert isinstance(snake_case		,	np.ndarray		)
											snake_case_					:Optional[int]		=     np.prod(boxes[:, 2:] - boxes[:, :2]		,	axis=1		)
											snake_case_					:Optional[int]		=     np.argsort(-areas		).tolist()
											snake_case_					:int		=     boxes[sorted_idxs] if boxes is not None else None
											snake_case_					:Optional[int]		=     obj_ids[sorted_idxs] if obj_ids is not None else None
											snake_case_					:int		=     obj_scores[sorted_idxs] if obj_scores is not None else None
											snake_case_					:str		=     attr_ids[sorted_idxs] if attr_ids is not None else None
											snake_case_					:Any		=     attr_scores[sorted_idxs] if attr_scores is not None else None

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






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

											snake_case_					:Optional[Any]		=     (ya - ya) / np.sqrt(self.height * self.width		)
											snake_case_					:Dict		=     self._change_color_brightness(snake_case		,	brightness_factor=0.7		)
											snake_case_					: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   lowerCAmelCase_							(			self:				List[str]		,	snake_case:				Union[str, Any]		,	snake_case:				Optional[int]		,	snake_case:				Union[str, Any]="g"		,	snake_case:				Tuple="left"		,	)  ->      str:
											snake_case_					:Optional[Any]		=     0
											snake_case_					:Union[str, Any]		=     self.font_size
											snake_case_					:Any		=     np.maximum(list(mplc.to_rgb(snake_case		)		)		,	0.2		)
											snake_case_					:Optional[Any]		=     max(0.8		,	np.max(snake_case		)		)
											snake_case_					:List[str]		=     {
											    """facecolor""": """black""",
											    """alpha""": self.alpha,
											    """pad""": self.pad,
											    """edgecolor""": """none""",
											}
											snake_case_,			snake_case_					:Optional[int]		=     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   lowerCAmelCase_							(			self:				Union[str, Any]		,	snake_case:				Tuple=None		)  ->      Dict:
											if saveas is None:
																	snake_case_					:int		=     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   lowerCAmelCase_							(			self:				str		,	snake_case:				List[Any]		,	snake_case:				Dict		,	snake_case:				Any		,	snake_case:				Tuple		)  ->      Dict:
											snake_case_					:int		=     [self.idaobj[i] for i in classes]
											snake_case_					:List[str]		=     [self.idaattr[i] for i in attr_classes]
											snake_case_					:List[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   lowerCAmelCase_							(			self:				Dict		,	snake_case:				Any		,	snake_case:				Dict		)  ->      Tuple:
											snake_case_					:Union[str, Any]		=     [self.idaobj[i] for i in classes]
											if scores is not None:
																	if labels is None:
																							snake_case_					:List[Any]		=     ["""{:.0f}%""".format(s * 100		) for s in scores]
																	else:
																							snake_case_					:Tuple		=     ["""{} {:.0f}%""".format(snake_case		,	s * 100		) for li, s in zip(snake_case		,	snake_case		)]
											return labels






					def   lowerCAmelCase_							(			self:				str		,	snake_case:				str=255		)  ->      List[str]:
											snake_case_					:Optional[Any]		=     np.random.randint(0		,	len(_COLORS		)		)
											snake_case_					:int		=     _COLORS[idx] * maximum
											if not self.rgb:
																	snake_case_					:List[Any]		=     ret[::-1]
											return ret






					def   lowerCAmelCase_							(			self:				Optional[int]		)  ->      Union[str, Any]:
											if not self.pynb:
																	snake_case_,			snake_case_					:str		=     self.canvas.print_to_buffer()
																	if (width, height) != (self.width, self.height):
																							snake_case_					:Optional[int]		=     cva.resize(self.img		,	(width, height)		)
																	else:
																							snake_case_					:List[Any]		=     self.img
											else:
																	snake_case_					:List[Any]		=     io.BytesIO()  # works for cairo backend
																	self.canvas.print_rgba(snake_case		)
																	snake_case_,			snake_case_					:Tuple		=     self.width, self.height
																	snake_case_					:Any		=     buf.getvalue()
																	snake_case_					:List[str]		=     self.img

											snake_case_					:Optional[int]		=     np.frombuffer(snake_case		,	dtype="""uint8"""		)
											snake_case_					:Optional[Any]		=     buffer.reshape(snake_case		,	snake_case		,	4		)
											snake_case_,			snake_case_					:Tuple		=     np.split(snake_case		,	[3]		,	axis=2		)

											try:
																	import numexpr as ne  # fuse them with numexpr

																	snake_case_					:Any		=     ne.evaluate("""img * (1 - alpha / 255.0) + rgb * (alpha / 255.0)"""		)
											except ImportError:
																	snake_case_					:Union[str, Any]		=     alpha.astype("""float32"""		) / 2_5_5.0
																	snake_case_					:int		=     img * (1 - alpha) + rgb * alpha

											return visualized_image.astype("""uint8"""		)






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

__a           =							(
    np.array(
        [
            0.0_00,
            0.4_47,
            0.7_41,
            0.8_50,
            0.3_25,
            0.0_98,
            0.9_29,
            0.6_94,
            0.1_25,
            0.4_94,
            0.1_84,
            0.5_56,
            0.4_66,
            0.6_74,
            0.1_88,
            0.3_01,
            0.7_45,
            0.9_33,
            0.6_35,
            0.0_78,
            0.1_84,
            0.3_00,
            0.3_00,
            0.3_00,
            0.6_00,
            0.6_00,
            0.6_00,
            1.0_00,
            0.0_00,
            0.0_00,
            1.0_00,
            0.5_00,
            0.0_00,
            0.7_49,
            0.7_49,
            0.0_00,
            0.0_00,
            1.0_00,
            0.0_00,
            0.0_00,
            0.0_00,
            1.0_00,
            0.6_67,
            0.0_00,
            1.0_00,
            0.3_33,
            0.3_33,
            0.0_00,
            0.3_33,
            0.6_67,
            0.0_00,
            0.3_33,
            1.0_00,
            0.0_00,
            0.6_67,
            0.3_33,
            0.0_00,
            0.6_67,
            0.6_67,
            0.0_00,
            0.6_67,
            1.0_00,
            0.0_00,
            1.0_00,
            0.3_33,
            0.0_00,
            1.0_00,
            0.6_67,
            0.0_00,
            1.0_00,
            1.0_00,
            0.0_00,
            0.0_00,
            0.3_33,
            0.5_00,
            0.0_00,
            0.6_67,
            0.5_00,
            0.0_00,
            1.0_00,
            0.5_00,
            0.3_33,
            0.0_00,
            0.5_00,
            0.3_33,
            0.3_33,
            0.5_00,
            0.3_33,
            0.6_67,
            0.5_00,
            0.3_33,
            1.0_00,
            0.5_00,
            0.6_67,
            0.0_00,
            0.5_00,
            0.6_67,
            0.3_33,
            0.5_00,
            0.6_67,
            0.6_67,
            0.5_00,
            0.6_67,
            1.0_00,
            0.5_00,
            1.0_00,
            0.0_00,
            0.5_00,
            1.0_00,
            0.3_33,
            0.5_00,
            1.0_00,
            0.6_67,
            0.5_00,
            1.0_00,
            1.0_00,
            0.5_00,
            0.0_00,
            0.3_33,
            1.0_00,
            0.0_00,
            0.6_67,
            1.0_00,
            0.0_00,
            1.0_00,
            1.0_00,
            0.3_33,
            0.0_00,
            1.0_00,
            0.3_33,
            0.3_33,
            1.0_00,
            0.3_33,
            0.6_67,
            1.0_00,
            0.3_33,
            1.0_00,
            1.0_00,
            0.6_67,
            0.0_00,
            1.0_00,
            0.6_67,
            0.3_33,
            1.0_00,
            0.6_67,
            0.6_67,
            1.0_00,
            0.6_67,
            1.0_00,
            1.0_00,
            1.0_00,
            0.0_00,
            1.0_00,
            1.0_00,
            0.3_33,
            1.0_00,
            1.0_00,
            0.6_67,
            1.0_00,
            0.3_33,
            0.0_00,
            0.0_00,
            0.5_00,
            0.0_00,
            0.0_00,
            0.6_67,
            0.0_00,
            0.0_00,
            0.8_33,
            0.0_00,
            0.0_00,
            1.0_00,
            0.0_00,
            0.0_00,
            0.0_00,
            0.1_67,
            0.0_00,
            0.0_00,
            0.3_33,
            0.0_00,
            0.0_00,
            0.5_00,
            0.0_00,
            0.0_00,
            0.6_67,
            0.0_00,
            0.0_00,
            0.8_33,
            0.0_00,
            0.0_00,
            1.0_00,
            0.0_00,
            0.0_00,
            0.0_00,
            0.1_67,
            0.0_00,
            0.0_00,
            0.3_33,
            0.0_00,
            0.0_00,
            0.5_00,
            0.0_00,
            0.0_00,
            0.6_67,
            0.0_00,
            0.0_00,
            0.8_33,
            0.0_00,
            0.0_00,
            1.0_00,
            0.0_00,
            0.0_00,
            0.0_00,
            0.1_43,
            0.1_43,
            0.1_43,
            0.8_57,
            0.8_57,
            0.8_57,
            1.0_00,
            1.0_00,
            1.0_00,
        ]
    )
    .astype(np.floataa)
    .reshape(-1, 3)
)
