code: 
  
  
  
  """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
  
  
  _lowerCAmelCase					:Optional[Any]  =      1_000
  class 							_UpperCAmelCase							:
  
  
  
  
  
       '''simple docstring'''
  
  
  
       def __init__(      self ,			A ,			A=1.2 ,			A="g" ,			A=0.5 ,			A="-" ,			A="test_out.jpg" ,			A=True ,			A=False ,			A=None ,			A=None ,			A=0.7 ,			)							->      str:
           if isinstance(A ,			torch.Tensor	):
               _UpperCAmelCase							:						Any       							=					img.numpy().astype('''np.uint8'''	)
           if isinstance(A ,			A	):
               _UpperCAmelCase							:						Tuple       							=					img_tensorize(A	)
           assert isinstance(A ,			np.ndarray	)
  
           _UpperCAmelCase							,       _UpperCAmelCase							:						Tuple       							=					img.shape[1], img.shape[0]
           _UpperCAmelCase							:						int       							=					mplfigure.Figure(frameon=A	)
           _UpperCAmelCase							:						Tuple       							=					fig.get_dpi()
           _UpperCAmelCase							:						Any       							=					(width * scale + 1E-2) / dpi
           _UpperCAmelCase							:						Tuple       							=					(height * scale + 1E-2) / dpi
           fig.set_size_inches(A ,			A	)
           _UpperCAmelCase							:						List[Any]       							=					fig.add_axes([0.0, 0.0, 1.0, 1.0]	)
           ax.axis('''off'''	)
           ax.set_xlim(0.0 ,			A	)
           ax.set_ylim(A	)
  
           _UpperCAmelCase							:						int       							=					saveas
           _UpperCAmelCase							:						Optional[int]       							=					rgb
           _UpperCAmelCase							:						Optional[int]       							=					pynb
           _UpperCAmelCase							:						int       							=					img
           _UpperCAmelCase							:						Optional[Any]       							=					edgecolor
           _UpperCAmelCase							:						Tuple       							=					0.5
           _UpperCAmelCase							:						Optional[Any]       							=					linestyle
           _UpperCAmelCase							:						str       							=					int(np.sqrt(min(A ,			A	)	) * scale // 3	)
           _UpperCAmelCase							:						Optional[Any]       							=					width
           _UpperCAmelCase							:						Dict       							=					height
           _UpperCAmelCase							:						Any       							=					scale
           _UpperCAmelCase							:						Dict       							=					fig
           _UpperCAmelCase							:						str       							=					ax
           _UpperCAmelCase							:						Tuple       							=					pad
           _UpperCAmelCase							:						Optional[int]       							=					idaobj
           _UpperCAmelCase							:						str       							=					idaattr
           _UpperCAmelCase							:						Tuple       							=					FigureCanvasAgg(A	)
  
  
  
  
  
       def 				__lowerCAmelCase			(      self ,			A ,			A=None	)							->      Optional[int]:
           if color is None:
               _UpperCAmelCase							:						str       							=					self.edgecolor
           ((_UpperCAmelCase)							,       (_UpperCAmelCase)							,       (_UpperCAmelCase)							,       (_UpperCAmelCase))							:						List[Any]       							=					box
           _UpperCAmelCase							:						List[str]       							=					xa - xa
           _UpperCAmelCase							:						Any       							=					ya - ya
           self.ax.add_patch(
               mpl.patches.Rectangle(
                   (xa, ya) ,			A ,			A ,			fill=A ,			edgecolor=A ,			linewidth=self.font_size // 3 ,			alpha=self.alpha ,			linestyle=self.linestyle ,			)	)
  
  
  
  
  
       def 				__lowerCAmelCase			(      self ,			A ,			A=None ,			A=None ,			A=None ,			A=None	)							->      List[Any]:
           if len(boxes.shape	) > 2:
               _UpperCAmelCase							:						Any       							=					boxes[0]
           if len(obj_ids.shape	) > 1:
               _UpperCAmelCase							:						int       							=					obj_ids[0]
           if len(obj_scores.shape	) > 1:
               _UpperCAmelCase							:						int       							=					obj_scores[0]
           if len(attr_ids.shape	) > 1:
               _UpperCAmelCase							:						Optional[int]       							=					attr_ids[0]
           if len(attr_scores.shape	) > 1:
               _UpperCAmelCase							:						Any       							=					attr_scores[0]
           if isinstance(A ,			torch.Tensor	):
               _UpperCAmelCase							:						Union[str, Any]       							=					boxes.numpy()
           if isinstance(A ,			A	):
               _UpperCAmelCase							:						Union[str, Any]       							=					np.array(A	)
           assert isinstance(A ,			np.ndarray	)
           _UpperCAmelCase							:						Union[str, Any]       							=					np.prod(boxes[:, 2:] - boxes[:, :2] ,			axis=1	)
           _UpperCAmelCase							:						Any       							=					np.argsort(-areas	).tolist()
           _UpperCAmelCase							:						Tuple       							=					boxes[sorted_idxs] if boxes is not None else None
           _UpperCAmelCase							:						Optional[Any]       							=					obj_ids[sorted_idxs] if obj_ids is not None else None
           _UpperCAmelCase							:						int       							=					obj_scores[sorted_idxs] if obj_scores is not None else None
           _UpperCAmelCase							:						List[Any]       							=					attr_ids[sorted_idxs] if attr_ids is not None else None
           _UpperCAmelCase							:						str       							=					attr_scores[sorted_idxs] if attr_scores is not None else None
  
           _UpperCAmelCase							:						Optional[int]       							=					[self._random_color(maximum=1	) for _ in range(len(A	)	)]
           _UpperCAmelCase							:						Tuple       							=					[assigned_colors[idx] for idx in sorted_idxs]
           if obj_ids is not None:
               _UpperCAmelCase							:						List[str]       							=					self._create_text_labels_attr(A ,			A ,			A ,			A	)
               for i in range(len(A	)	):
                   _UpperCAmelCase							:						Tuple       							=					assigned_colors[i]
                   self.add_box(boxes[i] ,			A	)
                   self.draw_labels(labels[i] ,			boxes[i] ,			A	)
  
  
  
  
  
       def 				__lowerCAmelCase			(      self ,			A ,			A ,			A	)							->      Any:
           _UpperCAmelCase							,       _UpperCAmelCase							,       _UpperCAmelCase							,       _UpperCAmelCase							:						List[str]       							=					box
           _UpperCAmelCase							:						Optional[Any]       							=					(xa, ya)
           _UpperCAmelCase							:						List[Any]       							=					(ya - ya) * (xa - xa)
           _UpperCAmelCase							:						List[Any]       							=					_SMALL_OBJ * self.scale
           if instance_area < small or ya - ya < 4_0 * self.scale:
               if ya >= self.height - 5:
                   _UpperCAmelCase							:						Tuple       							=					(xa, ya)
               else:
                   _UpperCAmelCase							:						Tuple       							=					(xa, ya)
  
           _UpperCAmelCase							:						Any       							=					(ya - ya) / np.sqrt(self.height * self.width	)
           _UpperCAmelCase							:						List[Any]       							=					self._change_color_brightness(A ,			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=A ,			position=A ,			color=A ,			)
  
  
  
  
  
       def 				__lowerCAmelCase			(      self ,			A ,			A ,			A="g" ,			A="left" ,			)							->      Dict:
           _UpperCAmelCase							:						Optional[int]       							=					0
           _UpperCAmelCase							:						str       							=					self.font_size
           _UpperCAmelCase							:						int       							=					np.maximum(list(mplc.to_rgb(A	)	) ,			0.2	)
           _UpperCAmelCase							:						Dict       							=					max(0.8 ,			np.max(A	)	)
           _UpperCAmelCase							:						int       							=					{
               '''facecolor''': '''black''',
               '''alpha''': self.alpha,
               '''pad''': self.pad,
               '''edgecolor''': '''none''',
           }
           _UpperCAmelCase							,       _UpperCAmelCase							:						Optional[Any]       							=					position
           self.ax.text(
               A ,			A ,			A ,			size=font_size * self.scale ,			family='''sans-serif''' ,			bbox=A ,			verticalalignment='''top''' ,			horizontalalignment=A ,			color=A ,			zorder=1_0 ,			rotation=A ,			)
  
  
  
  
  
       def 				__lowerCAmelCase			(      self ,			A=None	)							->      str:
           if saveas is None:
               _UpperCAmelCase							:						str       							=					self.saveas
           if saveas.lower().endswith('''.jpg'''	) or saveas.lower().endswith('''.png'''	):
               cva.imwrite(
                   A ,			self._get_buffer()[:, :, ::-1] ,			)
           else:
               self.fig.savefig(A	)
  
  
  
  
  
       def 				__lowerCAmelCase			(      self ,			A ,			A ,			A ,			A	)							->      int:
           _UpperCAmelCase							:						List[str]       							=					[self.idaobj[i] for i in classes]
           _UpperCAmelCase							:						Union[str, Any]       							=					[self.idaattr[i] for i in attr_classes]
           _UpperCAmelCase							:						List[Any]       							=					[
               f'{label} {score:.2f} {attr} {attr_score:.2f}'
               for label, score, attr, attr_score in zip(A ,			A ,			A ,			A	)
           ]
           return labels
  
  
  
  
  
       def 				__lowerCAmelCase			(      self ,			A ,			A	)							->      List[str]:
           _UpperCAmelCase							:						Tuple       							=					[self.idaobj[i] for i in classes]
           if scores is not None:
               if labels is None:
                   _UpperCAmelCase							:						Tuple       							=					['''{:.0f}%'''.format(s * 1_0_0	) for s in scores]
               else:
                   _UpperCAmelCase							:						Any       							=					['''{} {:.0f}%'''.format(A ,			s * 1_0_0	) for li, s in zip(A ,			A	)]
           return labels
  
  
  
  
  
       def 				__lowerCAmelCase			(      self ,			A=2_5_5	)							->      str:
           _UpperCAmelCase							:						Union[str, Any]       							=					np.random.randint(0 ,			len(_COLORS	)	)
           _UpperCAmelCase							:						Any       							=					_COLORS[idx] * maximum
           if not self.rgb:
               _UpperCAmelCase							:						Dict       							=					ret[::-1]
           return ret
  
  
  
  
  
       def 				__lowerCAmelCase			(      self	)							->      Optional[Any]:
           if not self.pynb:
               _UpperCAmelCase							,       _UpperCAmelCase							:						List[Any]       							=					self.canvas.print_to_buffer()
               if (width, height) != (self.width, self.height):
                   _UpperCAmelCase							:						List[str]       							=					cva.resize(self.img ,			(width, height)	)
               else:
                   _UpperCAmelCase							:						Optional[int]       							=					self.img
           else:
               _UpperCAmelCase							:						List[Any]       							=					io.BytesIO()  # works for cairo backend
               self.canvas.print_rgba(A	)
               _UpperCAmelCase							,       _UpperCAmelCase							:						Optional[int]       							=					self.width, self.height
               _UpperCAmelCase							:						Any       							=					buf.getvalue()
               _UpperCAmelCase							:						List[Any]       							=					self.img
  
           _UpperCAmelCase							:						int       							=					np.frombuffer(A ,			dtype='''uint8'''	)
           _UpperCAmelCase							:						List[Any]       							=					buffer.reshape(A ,			A ,			4	)
           _UpperCAmelCase							,       _UpperCAmelCase							:						Tuple       							=					np.split(A ,			[3] ,			axis=2	)
  
           try:
               import numexpr as ne  # fuse them with numexpr
  
               _UpperCAmelCase							:						Optional[Any]       							=					ne.evaluate('''img * (1 - alpha / 255.0) + rgb * (alpha / 255.0)'''	)
           except ImportError:
               _UpperCAmelCase							:						str       							=					alpha.astype('''float32'''	) / 255.0
               _UpperCAmelCase							:						List[str]       							=					img * (1 - alpha) + rgb * alpha
  
           return visualized_image.astype('''uint8'''	)
  
  
  
  
  
       def 				__lowerCAmelCase			(      self ,			A ,			A	)							->      List[str]:
           assert brightness_factor >= -1.0 and brightness_factor <= 1.0
           _UpperCAmelCase							:						Tuple       							=					mplc.to_rgb(A	)
           _UpperCAmelCase							:						str       							=					colorsys.rgb_to_hls(*mplc.to_rgb(A	)	)
           _UpperCAmelCase							:						Dict       							=					polygon_color[1] + (brightness_factor * polygon_color[1])
           _UpperCAmelCase							:						List[Any]       							=					0.0 if modified_lightness < 0.0 else modified_lightness
           _UpperCAmelCase							:						List[str]       							=					1.0 if modified_lightness > 1.0 else modified_lightness
           _UpperCAmelCase							:						Tuple       							=					colorsys.hls_to_rgb(polygon_color[0] ,			A ,			polygon_color[2]	)
           return modified_color
  
  
  
  _lowerCAmelCase					:int  =      (
      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)
  )
  
  
  
style_context: 
  
  
  
  """simple docstring"""
  # Lint as: python3
  import sys
  from collections.abc import Mapping
  from typing import TYPE_CHECKING
  
  import numpy as np
  import pyarrow as pa
  
  from .. import config
  from ..utils.py_utils import map_nested
  from .formatting import TensorFormatter
  
  
  if TYPE_CHECKING:
    import tensorflow as tf
  class 							_UpperCAmelCase							(				TensorFormatter[Mapping, '''tf.Tensor''', Mapping]   ):
  
  
  
  
  
       '''simple docstring'''
  
  
  
       def __init__(      self ,			A=None ,			**A	)							->      List[str]:
           super().__init__(features=A	)
           _UpperCAmelCase							:						Any       							=					tf_tensor_kwargs
           import tensorflow as tf  # noqa: import tf at initialization
  
  
  
  
  
       def 				__lowerCAmelCase			(      self ,			A	)							->      Optional[Any]:
           import tensorflow as tf
  
           if isinstance(A ,			A	) and column:
               if all(
                   isinstance(A ,			tf.Tensor	) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column	):
                   return tf.stack(A	)
               elif all(
                   isinstance(A ,			(tf.Tensor, tf.RaggedTensor)	) and x.ndim == 1 and x.dtype == column[0].dtype
                   for x in column	):
                   # only rag 1-D tensors, otherwise some dimensions become ragged even though they were consolidated
                   return tf.ragged.stack(A	)
  
           return column
  
  
  
  
  
       def 				__lowerCAmelCase			(      self ,			A	)							->      int:
           import tensorflow as tf
  
           if value is None:
               return value
  
           _UpperCAmelCase							:						Any       							=					{}
  
           if isinstance(A ,			(np.number, np.ndarray)	) and np.issubdtype(value.dtype ,			np.integer	):
               _UpperCAmelCase							:						Union[str, Any]       							=					{'''dtype''': tf.intaa}
           elif isinstance(A ,			(np.number, np.ndarray)	) and np.issubdtype(value.dtype ,			np.floating	):
               _UpperCAmelCase							:						Dict       							=					{'''dtype''': tf.floataa}
           elif config.PIL_AVAILABLE and "PIL" in sys.modules:
               import PIL.Image
  
               if isinstance(A ,			PIL.Image.Image	):
                   _UpperCAmelCase							:						Optional[int]       							=					np.asarray(A	)
  
           return tf.convert_to_tensor(A ,			**{**default_dtype, **self.tf_tensor_kwargs}	)
  
  
  
  
  
       def 				__lowerCAmelCase			(      self ,			A	)							->      Tuple:
           import tensorflow as tf
  
           # support for torch, tf, jax etc.
           if config.TORCH_AVAILABLE and "torch" in sys.modules:
               import torch
  
               if isinstance(A ,			torch.Tensor	):
                   return self._tensorize(data_struct.detach().cpu().numpy()[()]	)
           if hasattr(A ,			'''__array__'''	) and not isinstance(A ,			tf.Tensor	):
               _UpperCAmelCase							:						List[str]       							=					data_struct.__array__()
           # support for nested types like struct of list of struct
           if isinstance(A ,			np.ndarray	):
               if data_struct.dtype == object:  # tf tensors cannot be instantied from an array of objects
                   return self._consolidate([self.recursive_tensorize(A	) for substruct in data_struct]	)
           elif isinstance(A ,			(list, tuple)	):
               return self._consolidate([self.recursive_tensorize(A	) for substruct in data_struct]	)
           return self._tensorize(A	)
  
  
  
  
  
       def 				__lowerCAmelCase			(      self ,			A	)							->      Optional[int]:
           return map_nested(self._recursive_tensorize ,			A ,			map_list=A	)
  
  
  
  
  
       def 				__lowerCAmelCase			(      self ,			A	)							->      Mapping:
           _UpperCAmelCase							:						str       							=					self.numpy_arrow_extractor().extract_row(A	)
           _UpperCAmelCase							:						List[Any]       							=					self.python_features_decoder.decode_row(A	)
           return self.recursive_tensorize(A	)
  
  
  
  
  
       def 				__lowerCAmelCase			(      self ,			A	)							->      "tf.Tensor":
           _UpperCAmelCase							:						Union[str, Any]       							=					self.numpy_arrow_extractor().extract_column(A	)
           _UpperCAmelCase							:						Tuple       							=					self.python_features_decoder.decode_column(A ,			pa_table.column_names[0]	)
           _UpperCAmelCase							:						str       							=					self.recursive_tensorize(A	)
           _UpperCAmelCase							:						Optional[Any]       							=					self._consolidate(A	)
           return column
  
  
  
  
  
       def 				__lowerCAmelCase			(      self ,			A	)							->      Mapping:
           _UpperCAmelCase							:						Dict       							=					self.numpy_arrow_extractor().extract_batch(A	)
           _UpperCAmelCase							:						Tuple       							=					self.python_features_decoder.decode_batch(A	)
           _UpperCAmelCase							:						Union[str, Any]       							=					self.recursive_tensorize(A	)
           for column_name in batch:
               _UpperCAmelCase							:						str       							=					self._consolidate(batch[column_name]	)
           return batch
  
  
  