



import tempfile
import unittest

import numpy as np
import torch

from diffusers import DiffusionPipeline
from diffusers.models.attention_processor import Attention, AttnAddedKVProcessor

class 						__snake_case						(							unittest.TestCase     ):
       """simple docstring"""







       def  a		(		self			,   _UpperCamelCase = False      )			->       Optional[Any]:






              """simple docstring"""


              __snake_case					  =       10

              if only_cross_attention:
                     __snake_case					  =       12
              else:
                     # when only cross attention is not set, the cross attention dim must be the same as the query dim
                     __snake_case					  =       query_dim

              return {
                  "query_dim": query_dim,
                  "cross_attention_dim": cross_attention_dim,
                  "heads": 2,
                  "dim_head": 4,
                  "added_kv_proj_dim": 6,
                  "norm_num_groups": 1,
                  "only_cross_attention": only_cross_attention,
                  "processor": AttnAddedKVProcessor(),
              }


       def  a		(		self			,   _UpperCamelCase			,   _UpperCamelCase      )			->       Any:






              """simple docstring"""


              __snake_case					  =       2

              __snake_case					  =       torch.rand(_UpperCamelCase			,   _UpperCamelCase			,   3			,   2      )
              __snake_case					  =       torch.rand(_UpperCamelCase			,   4			,   _UpperCamelCase      )
              __snake_case					  =       None

              return {
                  "hidden_states": hidden_states,
                  "encoder_hidden_states": encoder_hidden_states,
                  "attention_mask": attention_mask,
              }






       def  a		(		self      )			->       int:






              """simple docstring"""


              torch.manual_seed(0      )

              __snake_case					  =       self.get_constructor_arguments(only_cross_attention=_UpperCamelCase      )
              __snake_case					  =       Attention(**_UpperCamelCase      )

              self.assertTrue(attn.to_k is not None      )
              self.assertTrue(attn.to_v is not None      )

              __snake_case					  =       self.get_forward_arguments(
                  query_dim=constructor_args["""query_dim"""]			,   added_kv_proj_dim=constructor_args["""added_kv_proj_dim"""]      )

              __snake_case					  =       attn(**_UpperCamelCase      )

              # only self attention

              torch.manual_seed(0      )

              __snake_case					  =       self.get_constructor_arguments(only_cross_attention=_UpperCamelCase      )
              __snake_case					  =       Attention(**_UpperCamelCase      )

              self.assertTrue(attn.to_k is None      )
              self.assertTrue(attn.to_v is None      )

              __snake_case					  =       self.get_forward_arguments(
                  query_dim=constructor_args["""query_dim"""]			,   added_kv_proj_dim=constructor_args["""added_kv_proj_dim"""]      )

              __snake_case					  =       attn(**_UpperCamelCase      )

              self.assertTrue((only_cross_attn_out != self_and_cross_attn_out).all()      )






class 						__snake_case						(							unittest.TestCase     ):
       """simple docstring"""







       def  a		(		self      )			->       Tuple:






              """simple docstring"""


              __snake_case					  =       DiffusionPipeline.from_pretrained("""hf-internal-testing/tiny-stable-diffusion-pipe"""			,   safety_checker=_UpperCamelCase      )

              __snake_case					  =       pipe(
                  """foo"""			,   num_inference_steps=2			,   generator=torch.Generator("""cpu"""      ).manual_seed(0      )			,   output_type="""np"""			,   ).images

              # the initial conversion succeeds
              __snake_case					  =       DiffusionPipeline.from_pretrained(
                  """hf-internal-testing/tiny-stable-diffusion-pipe"""			,   device_map="""sequential"""			,   safety_checker=_UpperCamelCase      )

              __snake_case					  =       pipe(
                  """foo"""			,   num_inference_steps=2			,   generator=torch.Generator("""cpu"""      ).manual_seed(0      )			,   output_type="""np"""			,   ).images

              with tempfile.TemporaryDirectory() as tmpdir:
                     # save the converted model
                     pipe.save_pretrained(_UpperCamelCase      )

                     # can also load the converted weights
                     __snake_case					  =       DiffusionPipeline.from_pretrained(_UpperCamelCase			,   device_map="""sequential"""			,   safety_checker=_UpperCamelCase      )

              __snake_case					  =       pipe(
                  """foo"""			,   num_inference_steps=2			,   generator=torch.Generator("""cpu"""      ).manual_seed(0      )			,   output_type="""np"""			,   ).images

              self.assertTrue(np.allclose(_UpperCamelCase			,   _UpperCamelCase			,   atol=1E-5      )      )
              self.assertTrue(np.allclose(_UpperCamelCase			,   _UpperCamelCase			,   atol=1E-5      )      )




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


UpperCamelCase__		   =    1000

class 						__snake_case						:
       """simple docstring"""







       def __init__(		self			,   _UpperCamelCase			,   _UpperCamelCase=1.2			,   _UpperCamelCase="g"			,   _UpperCamelCase=0.5			,   _UpperCamelCase="-"			,   _UpperCamelCase="test_out.jpg"			,   _UpperCamelCase=True			,   _UpperCamelCase=False			,   _UpperCamelCase=None			,   _UpperCamelCase=None			,   _UpperCamelCase=0.7			,   )			->       Union[str, Any]:






              """simple docstring"""


              if isinstance(_UpperCamelCase			,   torch.Tensor      ):
                     __snake_case					  =       img.numpy().astype("""np.uint8"""      )
              if isinstance(_UpperCamelCase			,   _UpperCamelCase      ):
                     __snake_case					  =       img_tensorize(_UpperCamelCase      )
              assert isinstance(_UpperCamelCase			,   np.ndarray      )

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

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


       def  a		(		self			,   _UpperCamelCase			,   _UpperCamelCase=None      )			->       int:






              """simple docstring"""


              if color is None:
                     __snake_case					  =       self.edgecolor
              ((__snake_case)  ,						(__snake_case)  ,						(__snake_case)  ,						(__snake_case))					  =       box
              __snake_case					  =       xa - xa
              __snake_case					  =       ya - ya
              self.ax.add_patch(
                  mpl.patches.Rectangle(
                      (xa, ya)			,   _UpperCamelCase			,   _UpperCamelCase			,   fill=_UpperCamelCase			,   edgecolor=_UpperCamelCase			,   linewidth=self.font_size // 3			,   alpha=self.alpha			,   linestyle=self.linestyle			,   )      )


       def  a		(		self			,   _UpperCamelCase			,   _UpperCamelCase=None			,   _UpperCamelCase=None			,   _UpperCamelCase=None			,   _UpperCamelCase=None      )			->       List[str]:






              """simple docstring"""


              if len(boxes.shape      ) > 2:
                     __snake_case					  =       boxes[0]
              if len(obj_ids.shape      ) > 1:
                     __snake_case					  =       obj_ids[0]
              if len(obj_scores.shape      ) > 1:
                     __snake_case					  =       obj_scores[0]
              if len(attr_ids.shape      ) > 1:
                     __snake_case					  =       attr_ids[0]
              if len(attr_scores.shape      ) > 1:
                     __snake_case					  =       attr_scores[0]
              if isinstance(_UpperCamelCase			,   torch.Tensor      ):
                     __snake_case					  =       boxes.numpy()
              if isinstance(_UpperCamelCase			,   _UpperCamelCase      ):
                     __snake_case					  =       np.array(_UpperCamelCase      )
              assert isinstance(_UpperCamelCase			,   np.ndarray      )
              __snake_case					  =       np.prod(boxes[:, 2:] - boxes[:, :2]			,   axis=1      )
              __snake_case					  =       np.argsort(-areas      ).tolist()
              __snake_case					  =       boxes[sorted_idxs] if boxes is not None else None
              __snake_case					  =       obj_ids[sorted_idxs] if obj_ids is not None else None
              __snake_case					  =       obj_scores[sorted_idxs] if obj_scores is not None else None
              __snake_case					  =       attr_ids[sorted_idxs] if attr_ids is not None else None
              __snake_case					  =       attr_scores[sorted_idxs] if attr_scores is not None else None

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


       def  a		(		self			,   _UpperCamelCase			,   _UpperCamelCase			,   _UpperCamelCase      )			->       Optional[Any]:






              """simple docstring"""


              __snake_case  ,						__snake_case  ,						__snake_case  ,						__snake_case					  =       box
              __snake_case					  =       (xa, ya)
              __snake_case					  =       (ya - ya) * (xa - xa)
              __snake_case					  =       _SMALL_OBJ * self.scale
              if instance_area < small or ya - ya < 40 * self.scale:
                     if ya >= self.height - 5:
                            __snake_case					  =       (xa, ya)
                     else:
                            __snake_case					  =       (xa, ya)

              __snake_case					  =       (ya - ya) / np.sqrt(self.height * self.width      )
              __snake_case					  =       self._change_color_brightness(_UpperCamelCase			,   brightness_factor=0.7      )
              __snake_case					  =       np.clip((height_ratio - 0.02) / 0.08 + 1			,   1.2			,   2      )
              font_size *= 0.75 * self.font_size

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


       def  a		(		self			,   _UpperCamelCase			,   _UpperCamelCase			,   _UpperCamelCase="g"			,   _UpperCamelCase="left"			,   )			->       List[Any]:






              """simple docstring"""


              __snake_case					  =       0
              __snake_case					  =       self.font_size
              __snake_case					  =       np.maximum(list(mplc.to_rgb(_UpperCamelCase      )      )			,   0.2      )
              __snake_case					  =       max(0.8			,   np.max(_UpperCamelCase      )      )
              __snake_case					  =       {
                  """facecolor""": """black""",
                  """alpha""": self.alpha,
                  """pad""": self.pad,
                  """edgecolor""": """none""",
              }
              __snake_case  ,						__snake_case					  =       position
              self.ax.text(
                  _UpperCamelCase			,   _UpperCamelCase			,   _UpperCamelCase			,   size=font_size * self.scale			,   family="""sans-serif"""			,   bbox=_UpperCamelCase			,   verticalalignment="""top"""			,   horizontalalignment=_UpperCamelCase			,   color=_UpperCamelCase			,   zorder=10			,   rotation=_UpperCamelCase			,   )


       def  a		(		self			,   _UpperCamelCase=None      )			->       str:






              """simple docstring"""


              if saveas is None:
                     __snake_case					  =       self.saveas
              if saveas.lower().endswith(""".jpg"""      ) or saveas.lower().endswith(""".png"""      ):
                     cva.imwrite(
                         _UpperCamelCase			,   self._get_buffer()[:, :, ::-1]			,   )
              else:
                     self.fig.savefig(_UpperCamelCase      )


       def  a		(		self			,   _UpperCamelCase			,   _UpperCamelCase			,   _UpperCamelCase			,   _UpperCamelCase      )			->       List[Any]:






              """simple docstring"""


              __snake_case					  =       [self.idaobj[i] for i in classes]
              __snake_case					  =       [self.idaattr[i] for i in attr_classes]
              __snake_case					  =       [
                  F'{label} {score:.2f} {attr} {attr_score:.2f}'
                  for label, score, attr, attr_score in zip(_UpperCamelCase			,   _UpperCamelCase			,   _UpperCamelCase			,   _UpperCamelCase      )
              ]
              return labels


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






              """simple docstring"""


              __snake_case					  =       [self.idaobj[i] for i in classes]
              if scores is not None:
                     if labels is None:
                            __snake_case					  =       ["""{:.0f}%""".format(s * 1_00      ) for s in scores]
                     else:
                            __snake_case					  =       ["""{} {:.0f}%""".format(_UpperCamelCase			,   s * 1_00      ) for li, s in zip(_UpperCamelCase			,   _UpperCamelCase      )]
              return labels


       def  a		(		self			,   _UpperCamelCase=2_55      )			->       List[Any]:






              """simple docstring"""


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


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






              """simple docstring"""


              if not self.pynb:
                     __snake_case  ,						__snake_case					  =       self.canvas.print_to_buffer()
                     if (width, height) != (self.width, self.height):
                            __snake_case					  =       cva.resize(self.img			,   (width, height)      )
                     else:
                            __snake_case					  =       self.img
              else:
                     __snake_case					  =       io.BytesIO()  # works for cairo backend
                     self.canvas.print_rgba(_UpperCamelCase      )
                     __snake_case  ,						__snake_case					  =       self.width, self.height
                     __snake_case					  =       buf.getvalue()
                     __snake_case					  =       self.img

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

              try:
                     import numexpr as ne  # fuse them with numexpr

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

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






       def  a		(		self			,   _UpperCamelCase			,   _UpperCamelCase      )			->       Dict:






              """simple docstring"""


              assert brightness_factor >= -1.0 and brightness_factor <= 1.0
              __snake_case					  =       mplc.to_rgb(_UpperCamelCase      )
              __snake_case					  =       colorsys.rgb_to_hls(*mplc.to_rgb(_UpperCamelCase      )      )
              __snake_case					  =       polygon_color[1] + (brightness_factor * polygon_color[1])
              __snake_case					  =       0.0 if modified_lightness < 0.0 else modified_lightness
              __snake_case					  =       1.0 if modified_lightness > 1.0 else modified_lightness
              __snake_case					  =       colorsys.hls_to_rgb(polygon_color[0]			,   _UpperCamelCase			,   polygon_color[2]      )
              return modified_color






UpperCamelCase__		   =    (
    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)
)

