





'''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_   :	Optional[Any]							   = 10_00


class 						__UpperCamelCase :






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



              """simple docstring"""







              if isinstance(lowerCAmelCase,	torch.Tensor						):
                     lowerCamelCase_							=img.numpy().astype('''np.uint8'''						)
              if isinstance(lowerCAmelCase,	lowerCAmelCase						):
                     lowerCamelCase_							=img_tensorize(lowerCAmelCase						)
              assert isinstance(lowerCAmelCase,	np.ndarray						)

              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,	lowerCAmelCase,	lowerCAmelCase=None						):



              """simple docstring"""







              if color is None:
                     lowerCamelCase_							=self.edgecolor
              (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,	lowerCAmelCase,	lowerCAmelCase=None,	lowerCAmelCase=None,	lowerCAmelCase=None,	lowerCAmelCase=None						):



              """simple docstring"""







              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,	lowerCAmelCase,	lowerCAmelCase,	lowerCAmelCase						):



              """simple docstring"""







              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.0_2) / 0.0_8 + 1,	1.2,	2						)
              font_size *= 0.7_5 * self.font_size

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






       def   lowercase__  (							self,	lowerCAmelCase,	lowerCAmelCase,	lowerCAmelCase="g",	lowerCAmelCase="left",	):



              """simple docstring"""







              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_							=position
              self.ax.text(
                  lowerCAmelCase,	lowerCAmelCase,	lowerCAmelCase,	size=font_size * self.scale,	family='''sans-serif''',	bbox=lowerCAmelCase,	verticalalignment='''top''',	horizontalalignment=lowerCAmelCase,	color=lowerCAmelCase,	zorder=10,	rotation=lowerCAmelCase,	)






       def   lowercase__  (							self,	lowerCAmelCase=None						):



              """simple docstring"""







              if saveas is None:
                     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,	lowerCAmelCase,	lowerCAmelCase,	lowerCAmelCase,	lowerCAmelCase						):



              """simple docstring"""







              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,	lowerCAmelCase,	lowerCAmelCase						):



              """simple docstring"""







              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,	lowerCAmelCase=255						):



              """simple docstring"""







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






       def   lowercase__  (							self						):



              """simple docstring"""







              if not self.pynb:
                     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_							=self.width, self.height
                     lowerCamelCase_							=buf.getvalue()
                     lowerCamelCase_							=self.img

              lowerCamelCase_							=np.frombuffer(lowerCAmelCase,	dtype='''uint8'''						)
              lowerCamelCase_							=buffer.reshape(lowerCAmelCase,	lowerCAmelCase,	4						)
              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'''						) / 2_5_5.0
                     lowerCamelCase_							=img * (1 - alpha) + rgb * alpha

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






       def   lowercase__  (							self,	lowerCAmelCase,	lowerCAmelCase						):



              """simple docstring"""







              assert brightness_factor >= -1.0 and brightness_factor <= 1.0
              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_   :	int							   = (
    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)
)










'''simple docstring'''




from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


a_   :	Union[str, Any]							   = {
    """configuration_openai""": ["""OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """OpenAIGPTConfig"""],
    """tokenization_openai""": ["""OpenAIGPTTokenizer"""],
}

try:
     if not is_tokenizers_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     a_   :	Optional[int]							   = ["""OpenAIGPTTokenizerFast"""]

try:
     if not is_torch_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     a_   :	int							   = [
         """OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST""",
         """OpenAIGPTDoubleHeadsModel""",
         """OpenAIGPTForSequenceClassification""",
         """OpenAIGPTLMHeadModel""",
         """OpenAIGPTModel""",
         """OpenAIGPTPreTrainedModel""",
         """load_tf_weights_in_openai_gpt""",
     ]

try:
     if not is_tf_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     a_   :	Dict							   = [
         """TF_OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST""",
         """TFOpenAIGPTDoubleHeadsModel""",
         """TFOpenAIGPTForSequenceClassification""",
         """TFOpenAIGPTLMHeadModel""",
         """TFOpenAIGPTMainLayer""",
         """TFOpenAIGPTModel""",
         """TFOpenAIGPTPreTrainedModel""",
     ]


if TYPE_CHECKING:
     from .configuration_openai import OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OpenAIGPTConfig
     from .tokenization_openai import OpenAIGPTTokenizer

     try:
          if not is_tokenizers_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .tokenization_openai_fast import OpenAIGPTTokenizerFast

     try:
          if not is_torch_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_openai import (
              OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST,
              OpenAIGPTDoubleHeadsModel,
              OpenAIGPTForSequenceClassification,
              OpenAIGPTLMHeadModel,
              OpenAIGPTModel,
              OpenAIGPTPreTrainedModel,
              load_tf_weights_in_openai_gpt,
          )

     try:
          if not is_tf_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_tf_openai import (
              TF_OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST,
              TFOpenAIGPTDoubleHeadsModel,
              TFOpenAIGPTForSequenceClassification,
              TFOpenAIGPTLMHeadModel,
              TFOpenAIGPTMainLayer,
              TFOpenAIGPTModel,
              TFOpenAIGPTPreTrainedModel,
          )

else:
     import sys

     a_   :	List[Any]							   = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)




