




"""simple docstring"""







import argparse
import inspect
import logging
from typing import Tuple

import numpy as np
import torch

from transformers import (
    AutoTokenizer,
    BloomForCausalLM,
    BloomTokenizerFast,
    CTRLLMHeadModel,
    CTRLTokenizer,
    GenerationMixin,
    GPTaLMHeadModel,
    GPTaTokenizer,
    GPTJForCausalLM,
    LlamaForCausalLM,
    LlamaTokenizer,
    OpenAIGPTLMHeadModel,
    OpenAIGPTTokenizer,
    OPTForCausalLM,
    TransfoXLLMHeadModel,
    TransfoXLTokenizer,
    XLMTokenizer,
    XLMWithLMHeadModel,
    XLNetLMHeadModel,
    XLNetTokenizer,
)
from transformers.modeling_outputs import CausalLMOutputWithPast


logging.basicConfig(
    format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
    datefmt='%m/%d/%Y %H:%M:%S',
    level=logging.INFO,
)
a								=							logging.getLogger(__name__)

a								=							int(1_0_0_0_0)  # Hardcoded max length to avoid infinite loop

a								=							{
    'gpt2': (GPTaLMHeadModel, GPTaTokenizer),
    'ctrl': (CTRLLMHeadModel, CTRLTokenizer),
    'openai-gpt': (OpenAIGPTLMHeadModel, OpenAIGPTTokenizer),
    'xlnet': (XLNetLMHeadModel, XLNetTokenizer),
    'transfo-xl': (TransfoXLLMHeadModel, TransfoXLTokenizer),
    'xlm': (XLMWithLMHeadModel, XLMTokenizer),
    'gptj': (GPTJForCausalLM, AutoTokenizer),
    'bloom': (BloomForCausalLM, BloomTokenizerFast),
    'llama': (LlamaForCausalLM, LlamaTokenizer),
    'opt': (OPTForCausalLM, GPTaTokenizer),
}

# Padding text to help Transformer-XL and XLNet with short prompts as proposed by Aman Rusia
# in https://github.com/rusiaaman/XLNet-gen#methodology
# and https://medium.com/@amanrusia/xlnet-speaks-comparison-to-gpt-2-ea1a4e9ba39e
a								=							'In 1991, the remains of Russian Tsar Nicholas II and his family\n(except for Alexei and Maria) are discovered.\nThe voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the\nremainder of the story. 1883 Western Siberia,\na young Grigori Rasputin is asked by his father and a group of men to perform magic.\nRasputin has a vision and denounces one of the men as a horse thief. Although his\nfather initially slaps him for making such an accusation, Rasputin watches as the\nman is chased outside and beaten. Twenty years later, Rasputin sees a vision of\nthe Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous,\nwith people, even a bishop, begging for his blessing. <eod> </s> <eos>'





def 							lowercase   (snake_case__				:	str	)       ->					Optional[int]:


				'''simple docstring'''






				np.random.seed(args.seed	)
				torch.manual_seed(args.seed	)
				if args.n_gpu > 0:
								torch.cuda.manual_seed_all(args.seed	)





def 							lowercase   (snake_case__				:	Any ,    snake_case__				:	Tuple ,    snake_case__				:	Tuple ,    snake_case__				:	Tuple	)       ->					Optional[int]:


				'''simple docstring'''






				if args.temperature > 0.7:
								logger.info("""CTRL typically works better with lower temperatures (and lower top_k)."""	)

				lowerCAmelCase		=			tokenizer.encode(snake_case__ ,    add_special_tokens=snake_case__	)
				if not any(encoded_prompt[0] == x for x in tokenizer.control_codes.values()	):
								logger.info("""WARNING! You are not starting your generation from a control code so you won't get good results"""	)
				return prompt_text





def 							lowercase   (snake_case__				:	Dict ,    snake_case__				:	Union[str, Any] ,    snake_case__				:	str ,    snake_case__				:	Dict	)       ->					int:


				'''simple docstring'''






				lowerCAmelCase		=			hasattr(model.config ,    """use_lang_emb"""	) and model.config.use_lang_emb
				if hasattr(model.config ,    """lang2id"""	) and use_lang_emb:
								lowerCAmelCase		=			model.config.langaid.keys()
								if args.xlm_language in available_languages:
												lowerCAmelCase		=			args.xlm_language
								else:
												lowerCAmelCase		=			None
												while language not in available_languages:
																lowerCAmelCase		=			input("""Using XLM. Select language in """ + str(list(snake_case__	)	) + """ >>> """	)

								lowerCAmelCase		=			model.config.langaid[language]
								# kwargs["language"] = tokenizer.lang2id[language]

				# TODO fix mask_token_id setup when configurations will be synchronized between models and tokenizers
				# XLM masked-language modeling (MLM) models need masked token
				# is_xlm_mlm = "mlm" in args.model_name_or_path
				# if is_xlm_mlm:
				#     kwargs["mask_token_id"] = tokenizer.mask_token_id

				return prompt_text





def 							lowercase   (snake_case__				:	Optional[int] ,    snake_case__				:	int ,    snake_case__				:	Optional[int] ,    snake_case__				:	List[Any]	)       ->					Tuple:


				'''simple docstring'''






				lowerCAmelCase		=			args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
				lowerCAmelCase		=			prefix + prompt_text
				return prompt_text





def 							lowercase   (snake_case__				:	List[Any] ,    snake_case__				:	List[Any] ,    snake_case__				:	Optional[int] ,    snake_case__				:	List[str]	)       ->					Dict:


				'''simple docstring'''






				lowerCAmelCase		=			args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
				lowerCAmelCase		=			prefix + prompt_text
				return prompt_text


a								=							{
    'ctrl': prepare_ctrl_input,
    'xlm': prepare_xlm_input,
    'xlnet': prepare_xlnet_input,
    'transfo-xl': prepare_transfoxl_input,
}





def 							lowercase   (snake_case__				:	Tuple ,    snake_case__				:	Optional[Any]	)       ->					List[str]:


				'''simple docstring'''






				if length < 0 and max_sequence_length > 0:
								lowerCAmelCase		=			max_sequence_length
				elif 0 < max_sequence_length < length:
								lowerCAmelCase		=			max_sequence_length  # No generation bigger than model size
				elif length < 0:
								lowerCAmelCase		=			MAX_LENGTH  # avoid infinite loop
				return length





def 							lowercase   (snake_case__				:	List[str]	)       ->					int:


				'''simple docstring'''






				lowerCAmelCase		=			None
				if hasattr(snake_case__ ,    """hidden_size"""	):
								lowerCAmelCase		=			model_config.hidden_size
				elif hasattr(snake_case__ ,    """n_embed"""	):
								lowerCAmelCase		=			model_config.n_embed
				elif hasattr(snake_case__ ,    """n_embd"""	):
								lowerCAmelCase		=			model_config.n_embd

				lowerCAmelCase		=			None
				if hasattr(snake_case__ ,    """num_attention_heads"""	):
								lowerCAmelCase		=			model_config.num_attention_heads
				elif hasattr(snake_case__ ,    """n_head"""	):
								lowerCAmelCase		=			model_config.n_head

				if embedding_size is None or num_head is None or num_head == 0:
								raise ValueError("""Check the model config"""	)

				lowerCAmelCase		=			int(embedding_size / num_head	)
				if hasattr(snake_case__ ,    """n_layer"""	):
								lowerCAmelCase		=			model_config.n_layer
				elif hasattr(snake_case__ ,    """num_hidden_layers"""	):
								lowerCAmelCase		=			model_config.num_hidden_layers
				else:
								raise ValueError("""Number of hidden layers couldn't be determined from the model config"""	)

				return num_layer, num_head, num_embedding_size_per_head





def 							lowercase   (snake_case__				:	List[str] ,    snake_case__				:	Any ,    snake_case__				:	int	)       ->					Optional[int]:


				'''simple docstring'''






				lowerCAmelCase	,  lowerCAmelCase	,  lowerCAmelCase		=			sparse_model_config(model.config	)
				if model.config.model_type == "bloom":
								lowerCAmelCase		=			tuple(
								    (
								        torch.empty(int(num_attention_heads * batch_size	) ,    snake_case__ ,    snake_case__	)
								        .to(model.dtype	)
								        .to(model.device	),
								        torch.empty(int(num_attention_heads * batch_size	) ,    snake_case__ ,    snake_case__	)
								        .to(model.dtype	)
								        .to(model.device	),
								    )
								    for _ in range(snake_case__	)	)
				else:
								lowerCAmelCase		=			tuple(
								    (
								        torch.empty(snake_case__ ,    snake_case__ ,    snake_case__ ,    snake_case__	)
								        .to(model.dtype	)
								        .to(model.device	),
								        torch.empty(snake_case__ ,    snake_case__ ,    snake_case__ ,    snake_case__	)
								        .to(model.dtype	)
								        .to(model.device	),
								    )
								    for _ in range(snake_case__	)	)
				return past_key_values





def 							lowercase   (snake_case__				:	Optional[int] ,    snake_case__				:	List[Any] ,    snake_case__				:	Any	)       ->					str:


				'''simple docstring'''






				lowerCAmelCase		=			len(snake_case__	)
				lowerCAmelCase		=			tokenizer.batch_encode_plus(snake_case__ ,    return_tensors="""pt"""	)
				lowerCAmelCase		=			dummy_input.to(model.device	)
				if model.config.use_cache:
								lowerCAmelCase		=			generate_past_key_values(snake_case__ ,    snake_case__ ,    1	)
				lowerCAmelCase		=			torch.cat(
				    [
				        torch.zeros(dummy_input["""attention_mask"""].shape[0] ,    1	)
				        .to(dummy_input["""attention_mask"""].dtype	)
				        .to(model.device	),
				        dummy_input["""attention_mask"""],
				    ] ,    -1 ,    )
				return dummy_input






class  SCREAMING_SNAKE_CASE__   (   _a   ):
						_a        =  ('_optimized', '_default')


						def __init__(							self			:     Optional[Any]  ,  lowerCAmelCase			:     Dict  ,  lowerCAmelCase			:     List[str]   ):
										lowerCAmelCase		=			optimized
										lowerCAmelCase		=			default


						def __call__(							self			:     List[Any]  ,  *lowerCAmelCase			:     Optional[Any]  ,  **lowerCAmelCase			:     str   ):
										if kwargs["past_key_values"] is None and self._default.config.use_cache:
														lowerCAmelCase		=			generate_past_key_values(self._default  ,  kwargs["""input_ids"""].shape[0]  ,  0   )
										kwargs.pop("""position_ids"""  ,  lowerCAmelCase   )
										for k in list(kwargs.keys()   ):
														if kwargs[k] is None or isinstance(kwargs[k]  ,  lowerCAmelCase   ):
																		kwargs.pop(lowerCAmelCase   )
										lowerCAmelCase		=			self._optimized(**lowerCAmelCase   )
										lowerCAmelCase		=			outputs[0]
										lowerCAmelCase		=			outputs[1]
										lowerCAmelCase		=			CausalLMOutputWithPast(
										    loss=lowerCAmelCase  ,  logits=lowerCAmelCase  ,  past_key_values=lowerCAmelCase  ,  hidden_states=lowerCAmelCase  ,  attentions=lowerCAmelCase  ,  )
										return fixed_output


						def __getattr__(							self			:     Optional[int]  ,  lowerCAmelCase			:     Tuple   ):
										return getattr(self._default  ,  lowerCAmelCase   )


						def 					__lowercase	(							self			:     int  ,  lowerCAmelCase			:     Any  ,  lowerCAmelCase			:     List[str]=None  ,  lowerCAmelCase			:     Dict=None  ,  lowerCAmelCase			:     Optional[int]=None  ,  **lowerCAmelCase			:     Dict   ):
										return self._default.prepare_inputs_for_generation(
										    lowerCAmelCase  ,  past_key_values=lowerCAmelCase  ,  inputs_embeds=lowerCAmelCase  ,  use_cache=lowerCAmelCase  ,  **lowerCAmelCase   )




						def 					__lowercase	(							self			:     Optional[int]  ,  lowerCAmelCase			:     Tuple[Tuple[torch.Tensor]]  ,  lowerCAmelCase			:     torch.Tensor   ):
										return self._default._reorder_cache(lowerCAmelCase  ,  lowerCAmelCase   )





def 							lowercase   ()       ->					List[str]:


				'''simple docstring'''






				lowerCAmelCase		=			argparse.ArgumentParser()
				parser.add_argument(
				    """--model_type""" ,    default=snake_case__ ,    type=snake_case__ ,    required=snake_case__ ,    help="""Model type selected in the list: """ + """, """.join(MODEL_CLASSES.keys()	) ,    )
				parser.add_argument(
				    """--model_name_or_path""" ,    default=snake_case__ ,    type=snake_case__ ,    required=snake_case__ ,    help="""Path to pre-trained model or shortcut name selected in the list: """ + """, """.join(MODEL_CLASSES.keys()	) ,    )

				parser.add_argument("""--prompt""" ,    type=snake_case__ ,    default=""""""	)
				parser.add_argument("""--length""" ,    type=snake_case__ ,    default=20	)
				parser.add_argument("""--stop_token""" ,    type=snake_case__ ,    default=snake_case__ ,    help="""Token at which text generation is stopped"""	)

				parser.add_argument(
				    """--temperature""" ,    type=snake_case__ ,    default=1.0 ,    help="""temperature of 1.0 has no effect, lower tend toward greedy sampling""" ,    )
				parser.add_argument(
				    """--repetition_penalty""" ,    type=snake_case__ ,    default=1.0 ,    help="""primarily useful for CTRL model; in that case, use 1.2"""	)
				parser.add_argument("""--k""" ,    type=snake_case__ ,    default=0	)
				parser.add_argument("""--p""" ,    type=snake_case__ ,    default=0.9	)

				parser.add_argument("""--prefix""" ,    type=snake_case__ ,    default="""""" ,    help="""Text added prior to input."""	)
				parser.add_argument("""--padding_text""" ,    type=snake_case__ ,    default="""""" ,    help="""Deprecated, the use of `--prefix` is preferred."""	)
				parser.add_argument("""--xlm_language""" ,    type=snake_case__ ,    default="""""" ,    help="""Optional language when used with the XLM model."""	)

				parser.add_argument("""--seed""" ,    type=snake_case__ ,    default=42 ,    help="""random seed for initialization"""	)
				parser.add_argument("""--no_cuda""" ,    action="""store_true""" ,    help="""Avoid using CUDA when available"""	)
				parser.add_argument("""--num_return_sequences""" ,    type=snake_case__ ,    default=1 ,    help="""The number of samples to generate."""	)
				parser.add_argument(
				    """--fp16""" ,    action="""store_true""" ,    help="""Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit""" ,    )
				parser.add_argument("""--jit""" ,    action="""store_true""" ,    help="""Whether or not to use jit trace to accelerate inference"""	)
				lowerCAmelCase		=			parser.parse_args()

				lowerCAmelCase		=			torch.device("""cuda""" if torch.cuda.is_available() and not args.no_cuda else """cpu"""	)
				lowerCAmelCase		=			0 if args.no_cuda else torch.cuda.device_count()

				logger.warning(f'''device: {args.device}, n_gpu: {args.n_gpu}, 16-bits training: {args.fpaa}'''	)

				set_seed(snake_case__	)

				# Initialize the model and tokenizer
				try:
								lowerCAmelCase		=			args.model_type.lower()
								lowerCAmelCase	,  lowerCAmelCase		=			MODEL_CLASSES[args.model_type]
				except KeyError:
								raise KeyError("""the model {} you specified is not supported. You are welcome to add it and open a PR :)"""	)

				lowerCAmelCase		=			tokenizer_class.from_pretrained(args.model_name_or_path	)
				if tokenizer.pad_token is None:
								lowerCAmelCase		=			tokenizer.eos_token
				lowerCAmelCase		=			model_class.from_pretrained(args.model_name_or_path	)
				model.to(args.device	)

				if args.fpaa:
								model.half()
				lowerCAmelCase		=			getattr(model.config ,    """max_position_embeddings""" ,    0	)
				lowerCAmelCase		=			adjust_length_to_model(args.length ,    max_sequence_length=snake_case__	)
				logger.info(snake_case__	)

				lowerCAmelCase		=			args.prompt if args.prompt else input("""Model prompt >>> """	)

				# Different models need different input formatting and/or extra arguments
				lowerCAmelCase		=			args.model_type in PREPROCESSING_FUNCTIONS.keys()
				if requires_preprocessing:
								lowerCAmelCase		=			PREPROCESSING_FUNCTIONS.get(args.model_type	)
								lowerCAmelCase		=			prepare_input(snake_case__ ,    snake_case__ ,    snake_case__ ,    snake_case__	)

								if model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
												lowerCAmelCase		=			{"""add_space_before_punct_symbol""": True}
								else:
												lowerCAmelCase		=			{}

								lowerCAmelCase		=			tokenizer.encode(
								    snake_case__ ,    add_special_tokens=snake_case__ ,    return_tensors="""pt""" ,    **snake_case__	)
				else:
								lowerCAmelCase		=			args.prefix if args.prefix else args.padding_text
								lowerCAmelCase		=			tokenizer.encode(prefix + prompt_text ,    add_special_tokens=snake_case__ ,    return_tensors="""pt"""	)
				lowerCAmelCase		=			encoded_prompt.to(args.device	)

				if encoded_prompt.size()[-1] == 0:
								lowerCAmelCase		=			None
				else:
								lowerCAmelCase		=			encoded_prompt

				if args.jit:
								lowerCAmelCase		=			["""enable jit"""]
								lowerCAmelCase		=			prepare_jit_inputs(snake_case__ ,    snake_case__ ,    snake_case__	)
								torch._C._jit_set_texpr_fuser_enabled(snake_case__	)
								lowerCAmelCase		=			False
								if hasattr(snake_case__ ,    """forward"""	):
												lowerCAmelCase		=			inspect.signature(model.forward	)
								else:
												lowerCAmelCase		=			inspect.signature(model.__call__	)
								lowerCAmelCase		=			tuple(jit_inputs[key] for key in sig.parameters if jit_inputs.get(snake_case__ ,    snake_case__	) is not None	)
								lowerCAmelCase		=			torch.jit.trace(snake_case__ ,    snake_case__ ,    strict=snake_case__	)
								lowerCAmelCase		=			torch.jit.freeze(traced_model.eval()	)
								traced_model(*snake_case__	)
								traced_model(*snake_case__	)

								lowerCAmelCase		=			_ModelFallbackWrapper(snake_case__ ,    snake_case__	)

				lowerCAmelCase		=			model.generate(
				    input_ids=snake_case__ ,    max_length=args.length + len(encoded_prompt[0]	) ,    temperature=args.temperature ,    top_k=args.k ,    top_p=args.p ,    repetition_penalty=args.repetition_penalty ,    do_sample=snake_case__ ,    num_return_sequences=args.num_return_sequences ,    )

				# Remove the batch dimension when returning multiple sequences
				if len(output_sequences.shape	) > 2:
								output_sequences.squeeze_()

				lowerCAmelCase		=			[]

				for generated_sequence_idx, generated_sequence in enumerate(snake_case__	):
								print(f'''=== GENERATED SEQUENCE {generated_sequence_idx + 1} ==='''	)
								lowerCAmelCase		=			generated_sequence.tolist()

								# Decode text
								lowerCAmelCase		=			tokenizer.decode(snake_case__ ,    clean_up_tokenization_spaces=snake_case__	)

								# Remove all text after the stop token
								lowerCAmelCase		=			text[: text.find(args.stop_token	) if args.stop_token else None]

								# Add the prompt at the beginning of the sequence. Remove the excess text that was used for pre-processing
								lowerCAmelCase		=			(
								    prompt_text + text[len(tokenizer.decode(encoded_prompt[0] ,    clean_up_tokenization_spaces=snake_case__	)	) :]
								)

								generated_sequences.append(snake_case__	)
								print(snake_case__	)

				return generated_sequences


if __name__ == "__main__":
		main()











"""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								=							1_0_0_0






class  SCREAMING_SNAKE_CASE__   :


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

										lowerCAmelCase	,  lowerCAmelCase		=			img.shape[1], img.shape[0]
										lowerCAmelCase		=			mplfigure.Figure(frameon=lowerCAmelCase   )
										lowerCAmelCase		=			fig.get_dpi()
										lowerCAmelCase		=			(width * scale + 1e-2) / dpi
										lowerCAmelCase		=			(height * scale + 1e-2) / dpi
										fig.set_size_inches(lowerCAmelCase  ,  lowerCAmelCase   )
										lowerCAmelCase		=			fig.add_axes([0.0, 0.0, 1.0, 1.0]   )
										ax.axis("""off"""   )
										ax.set_xlim(0.0  ,  lowerCAmelCase   )
										ax.set_ylim(lowerCAmelCase   )

										lowerCAmelCase		=			saveas
										lowerCAmelCase		=			rgb
										lowerCAmelCase		=			pynb
										lowerCAmelCase		=			img
										lowerCAmelCase		=			edgecolor
										lowerCAmelCase		=			0.5
										lowerCAmelCase		=			linestyle
										lowerCAmelCase		=			int(np.sqrt(min(lowerCAmelCase  ,  lowerCAmelCase   )   ) * scale // 3   )
										lowerCAmelCase		=			width
										lowerCAmelCase		=			height
										lowerCAmelCase		=			scale
										lowerCAmelCase		=			fig
										lowerCAmelCase		=			ax
										lowerCAmelCase		=			pad
										lowerCAmelCase		=			idaobj
										lowerCAmelCase		=			idaattr
										lowerCAmelCase		=			FigureCanvasAgg(lowerCAmelCase   )


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

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


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

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


						def 					__lowercase	(							self			:     Any  ,  lowerCAmelCase			:     str=255   ):
										lowerCAmelCase		=			np.random.randint(0  ,  len(_COLORS   )   )
										lowerCAmelCase		=			_COLORS[idx] * maximum
										if not self.rgb:
														lowerCAmelCase		=			ret[::-1]
										return ret


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

										lowerCAmelCase		=			np.frombuffer(lowerCAmelCase  ,  dtype="""uint8"""   )
										lowerCAmelCase		=			buffer.reshape(lowerCAmelCase  ,  lowerCAmelCase  ,  4   )
										lowerCAmelCase	,  lowerCAmelCase		=			np.split(lowerCAmelCase  ,  [3]  ,  axis=2   )

										try:
														import numexpr as ne  # fuse them with numexpr

														lowerCAmelCase		=			ne.evaluate("""img * (1 - alpha / 255.0) + rgb * (alpha / 255.0)"""   )
										except ImportError:
														lowerCAmelCase		=			alpha.astype("""float32"""   ) / 255.0
														lowerCAmelCase		=			img * (1 - alpha) + rgb * alpha

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




						def 					__lowercase	(							self			:     List[str]  ,  lowerCAmelCase			:     Optional[Any]  ,  lowerCAmelCase			:     Optional[int]   ):
										assert brightness_factor >= -1.0 and brightness_factor <= 1.0
										lowerCAmelCase		=			mplc.to_rgb(lowerCAmelCase   )
										lowerCAmelCase		=			colorsys.rgb_to_hls(*mplc.to_rgb(lowerCAmelCase   )   )
										lowerCAmelCase		=			polygon_color[1] + (brightness_factor * polygon_color[1])
										lowerCAmelCase		=			0.0 if modified_lightness < 0.0 else modified_lightness
										lowerCAmelCase		=			1.0 if modified_lightness > 1.0 else modified_lightness
										lowerCAmelCase		=			colorsys.hls_to_rgb(polygon_color[0]  ,  lowerCAmelCase  ,  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)
)





