


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


_SCREAMING_SNAKE_CASE          = 1_0_0_0


class     lowerCamelCase_   :




 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     ,     ):
   if isinstance(_UpperCAmelCase     ,     torch.Tensor       ):
     __UpperCAmelCase  :     Dict		=    img.numpy().astype('np.uint8'       )
   if isinstance(_UpperCAmelCase     ,     _UpperCAmelCase       ):
     __UpperCAmelCase  :     int		=    img_tensorize(_UpperCAmelCase       )
   assert isinstance(_UpperCAmelCase     ,     np.ndarray       )

   __UpperCAmelCase  :     Dict		=    img.shape[1], img.shape[0]
   __UpperCAmelCase  :     int		=    mplfigure.Figure(frameon=_UpperCAmelCase       )
   __UpperCAmelCase  :     Any		=    fig.get_dpi()
   __UpperCAmelCase  :     Tuple		=    (width * scale + 1E-2) / dpi
   __UpperCAmelCase  :     Any		=    (height * scale + 1E-2) / dpi
   fig.set_size_inches(_UpperCAmelCase     ,     _UpperCAmelCase       )
   __UpperCAmelCase  :     List[str]		=    fig.add_axes([0.0, 0.0, 1.0, 1.0]       )
   ax.axis('off'       )
   ax.set_xlim(0.0     ,     _UpperCAmelCase       )
   ax.set_ylim(_UpperCAmelCase       )

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




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

   __UpperCAmelCase  :     Dict		=    [self._random_color(maximum=1       ) for _ in range(len(_UpperCAmelCase       )       )]
   __UpperCAmelCase  :     str		=    [assigned_colors[idx] for idx in sorted_idxs]
   if obj_ids is not None:
     __UpperCAmelCase  :     Optional[Any]		=    self._create_text_labels_attr(_UpperCAmelCase     ,     _UpperCAmelCase     ,     _UpperCAmelCase     ,     _UpperCAmelCase       )
     for i in range(len(_UpperCAmelCase       )       ):
       __UpperCAmelCase  :     Tuple		=    assigned_colors[i]
       self.add_box(boxes[i]     ,     _UpperCAmelCase       )
       self.draw_labels(labels[i]     ,     boxes[i]     ,     _UpperCAmelCase       )




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

   __UpperCAmelCase  :     Any		=    (ya - ya) / np.sqrt(self.height * self.width       )
   __UpperCAmelCase  :     Dict		=    self._change_color_brightness(_UpperCAmelCase     ,     brightness_factor=0.7       )
   __UpperCAmelCase  :     Optional[int]		=    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=_UpperCAmelCase     ,     position=_UpperCAmelCase     ,     color=_UpperCAmelCase     ,     )




 def 						a					( self     ,     _UpperCAmelCase     ,     _UpperCAmelCase     ,     _UpperCAmelCase="g"     ,     _UpperCAmelCase="left"     ,     ):
   __UpperCAmelCase  :     Any		=    0
   __UpperCAmelCase  :     Dict		=    self.font_size
   __UpperCAmelCase  :     Optional[int]		=    np.maximum(list(mplc.to_rgb(_UpperCAmelCase       )       )     ,     0.2       )
   __UpperCAmelCase  :     Any		=    max(0.8     ,     np.max(_UpperCAmelCase       )       )
   __UpperCAmelCase  :     Optional[int]		=    {
       'facecolor': 'black',
       'alpha': self.alpha,
       'pad': self.pad,
       'edgecolor': 'none',
   }
   __UpperCAmelCase  :     Optional[int]		=    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       ):
   if saveas is None:
     __UpperCAmelCase  :     Optional[int]		=    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       ):
   __UpperCAmelCase  :     List[str]		=    [self.idaobj[i] for i in classes]
   __UpperCAmelCase  :     List[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(_UpperCAmelCase     ,     _UpperCAmelCase     ,     _UpperCAmelCase     ,     _UpperCAmelCase       )
   ]
   return labels




 def 						a					( self     ,     _UpperCAmelCase     ,     _UpperCAmelCase       ):
   __UpperCAmelCase  :     Union[str, Any]		=    [self.idaobj[i] for i in classes]
   if scores is not None:
     if labels is None:
       __UpperCAmelCase  :     Any		=    ['{:.0f}%'.format(s * 100       ) for s in scores]
     else:
       __UpperCAmelCase  :     int		=    ['{} {:.0f}%'.format(_UpperCAmelCase     ,     s * 100       ) for li, s in zip(_UpperCAmelCase     ,     _UpperCAmelCase       )]
   return labels




 def 						a					( self     ,     _UpperCAmelCase=255       ):
   __UpperCAmelCase  :     Optional[int]		=    np.random.randint(0     ,     len(_COLORS       )       )
   __UpperCAmelCase  :     List[Any]		=    _COLORS[idx] * maximum
   if not self.rgb:
     __UpperCAmelCase  :     Dict		=    ret[::-1]
   return ret




 def 						a					( self       ):
   if not self.pynb:
     __UpperCAmelCase  :     Optional[Any]		=    self.canvas.print_to_buffer()
     if (width, height) != (self.width, self.height):
       __UpperCAmelCase  :     int		=    cva.resize(self.img     ,     (width, height)       )
     else:
       __UpperCAmelCase  :     List[str]		=    self.img
   else:
     __UpperCAmelCase  :     Dict		=    io.BytesIO()  # works for cairo backend
     self.canvas.print_rgba(_UpperCAmelCase       )
     __UpperCAmelCase  :     Any		=    self.width, self.height
     __UpperCAmelCase  :     str		=    buf.getvalue()
     __UpperCAmelCase  :     Dict		=    self.img

   __UpperCAmelCase  :     Any		=    np.frombuffer(_UpperCAmelCase     ,     dtype='uint8'       )
   __UpperCAmelCase  :     Dict		=    buffer.reshape(_UpperCAmelCase     ,     _UpperCAmelCase     ,     4       )
   __UpperCAmelCase  :     List[Any]		=    np.split(_UpperCAmelCase     ,     [3]     ,     axis=2       )

   try:
     import numexpr as ne  # fuse them with numexpr

     __UpperCAmelCase  :     Tuple		=    ne.evaluate('img * (1 - alpha / 255.0) + rgb * (alpha / 255.0)'       )
   except ImportError:
     __UpperCAmelCase  :     Optional[int]		=    alpha.astype('float32'       ) / 255.0
     __UpperCAmelCase  :     Any		=    img * (1 - alpha) + rgb * alpha

   return visualized_image.astype('uint8'       )




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



_SCREAMING_SNAKE_CASE          = (
    np.array(
        [
            0.0_0_0,
            0.4_4_7,
            0.7_4_1,
            0.8_5_0,
            0.3_2_5,
            0.0_9_8,
            0.9_2_9,
            0.6_9_4,
            0.1_2_5,
            0.4_9_4,
            0.1_8_4,
            0.5_5_6,
            0.4_6_6,
            0.6_7_4,
            0.1_8_8,
            0.3_0_1,
            0.7_4_5,
            0.9_3_3,
            0.6_3_5,
            0.0_7_8,
            0.1_8_4,
            0.3_0_0,
            0.3_0_0,
            0.3_0_0,
            0.6_0_0,
            0.6_0_0,
            0.6_0_0,
            1.0_0_0,
            0.0_0_0,
            0.0_0_0,
            1.0_0_0,
            0.5_0_0,
            0.0_0_0,
            0.7_4_9,
            0.7_4_9,
            0.0_0_0,
            0.0_0_0,
            1.0_0_0,
            0.0_0_0,
            0.0_0_0,
            0.0_0_0,
            1.0_0_0,
            0.6_6_7,
            0.0_0_0,
            1.0_0_0,
            0.3_3_3,
            0.3_3_3,
            0.0_0_0,
            0.3_3_3,
            0.6_6_7,
            0.0_0_0,
            0.3_3_3,
            1.0_0_0,
            0.0_0_0,
            0.6_6_7,
            0.3_3_3,
            0.0_0_0,
            0.6_6_7,
            0.6_6_7,
            0.0_0_0,
            0.6_6_7,
            1.0_0_0,
            0.0_0_0,
            1.0_0_0,
            0.3_3_3,
            0.0_0_0,
            1.0_0_0,
            0.6_6_7,
            0.0_0_0,
            1.0_0_0,
            1.0_0_0,
            0.0_0_0,
            0.0_0_0,
            0.3_3_3,
            0.5_0_0,
            0.0_0_0,
            0.6_6_7,
            0.5_0_0,
            0.0_0_0,
            1.0_0_0,
            0.5_0_0,
            0.3_3_3,
            0.0_0_0,
            0.5_0_0,
            0.3_3_3,
            0.3_3_3,
            0.5_0_0,
            0.3_3_3,
            0.6_6_7,
            0.5_0_0,
            0.3_3_3,
            1.0_0_0,
            0.5_0_0,
            0.6_6_7,
            0.0_0_0,
            0.5_0_0,
            0.6_6_7,
            0.3_3_3,
            0.5_0_0,
            0.6_6_7,
            0.6_6_7,
            0.5_0_0,
            0.6_6_7,
            1.0_0_0,
            0.5_0_0,
            1.0_0_0,
            0.0_0_0,
            0.5_0_0,
            1.0_0_0,
            0.3_3_3,
            0.5_0_0,
            1.0_0_0,
            0.6_6_7,
            0.5_0_0,
            1.0_0_0,
            1.0_0_0,
            0.5_0_0,
            0.0_0_0,
            0.3_3_3,
            1.0_0_0,
            0.0_0_0,
            0.6_6_7,
            1.0_0_0,
            0.0_0_0,
            1.0_0_0,
            1.0_0_0,
            0.3_3_3,
            0.0_0_0,
            1.0_0_0,
            0.3_3_3,
            0.3_3_3,
            1.0_0_0,
            0.3_3_3,
            0.6_6_7,
            1.0_0_0,
            0.3_3_3,
            1.0_0_0,
            1.0_0_0,
            0.6_6_7,
            0.0_0_0,
            1.0_0_0,
            0.6_6_7,
            0.3_3_3,
            1.0_0_0,
            0.6_6_7,
            0.6_6_7,
            1.0_0_0,
            0.6_6_7,
            1.0_0_0,
            1.0_0_0,
            1.0_0_0,
            0.0_0_0,
            1.0_0_0,
            1.0_0_0,
            0.3_3_3,
            1.0_0_0,
            1.0_0_0,
            0.6_6_7,
            1.0_0_0,
            0.3_3_3,
            0.0_0_0,
            0.0_0_0,
            0.5_0_0,
            0.0_0_0,
            0.0_0_0,
            0.6_6_7,
            0.0_0_0,
            0.0_0_0,
            0.8_3_3,
            0.0_0_0,
            0.0_0_0,
            1.0_0_0,
            0.0_0_0,
            0.0_0_0,
            0.0_0_0,
            0.1_6_7,
            0.0_0_0,
            0.0_0_0,
            0.3_3_3,
            0.0_0_0,
            0.0_0_0,
            0.5_0_0,
            0.0_0_0,
            0.0_0_0,
            0.6_6_7,
            0.0_0_0,
            0.0_0_0,
            0.8_3_3,
            0.0_0_0,
            0.0_0_0,
            1.0_0_0,
            0.0_0_0,
            0.0_0_0,
            0.0_0_0,
            0.1_6_7,
            0.0_0_0,
            0.0_0_0,
            0.3_3_3,
            0.0_0_0,
            0.0_0_0,
            0.5_0_0,
            0.0_0_0,
            0.0_0_0,
            0.6_6_7,
            0.0_0_0,
            0.0_0_0,
            0.8_3_3,
            0.0_0_0,
            0.0_0_0,
            1.0_0_0,
            0.0_0_0,
            0.0_0_0,
            0.0_0_0,
            0.1_4_3,
            0.1_4_3,
            0.1_4_3,
            0.8_5_7,
            0.8_5_7,
            0.8_5_7,
            1.0_0_0,
            1.0_0_0,
            1.0_0_0,
        ]
    )
    .astype(np.floataa)
    .reshape(-1, 3)
)








from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxSeqaSeqConfigWithPast
from ...utils import logging


_SCREAMING_SNAKE_CASE          = logging.get_logger(__name__)


class     lowerCamelCase_   ( _lowerCAmelCase):
 _lowerCAmelCase       		=  '''mt5'''
 _lowerCAmelCase       		=  ['''past_key_values''']




 def __init__( self     ,     _UpperCAmelCase=250_112     ,     _UpperCAmelCase=512     ,     _UpperCAmelCase=64     ,     _UpperCAmelCase=1_024     ,     _UpperCAmelCase=8     ,     _UpperCAmelCase=None     ,     _UpperCAmelCase=6     ,     _UpperCAmelCase=32     ,     _UpperCAmelCase=128     ,     _UpperCAmelCase=0.1     ,     _UpperCAmelCase=1E-6     ,     _UpperCAmelCase=1.0     ,     _UpperCAmelCase="gated-gelu"     ,     _UpperCAmelCase=True     ,     _UpperCAmelCase=True     ,     _UpperCAmelCase="T5Tokenizer"     ,     _UpperCAmelCase=False     ,     _UpperCAmelCase=0     ,     _UpperCAmelCase=1     ,     _UpperCAmelCase=0     ,     **_UpperCAmelCase     ,     ):
   super().__init__(
       is_encoder_decoder=_UpperCAmelCase     ,     tokenizer_class=_UpperCAmelCase     ,     tie_word_embeddings=_UpperCAmelCase     ,     pad_token_id=_UpperCAmelCase     ,     eos_token_id=_UpperCAmelCase     ,     decoder_start_token_id=_UpperCAmelCase     ,     **_UpperCAmelCase     ,     )
   __UpperCAmelCase  :     Dict		=    vocab_size
   __UpperCAmelCase  :     List[str]		=    d_model
   __UpperCAmelCase  :     str		=    d_kv
   __UpperCAmelCase  :     List[str]		=    d_ff
   __UpperCAmelCase  :     int		=    num_layers
   __UpperCAmelCase  :     List[Any]		=    (
       num_decoder_layers if num_decoder_layers is not None else self.num_layers
   )  # default = symmetry
   __UpperCAmelCase  :     List[Any]		=    num_heads
   __UpperCAmelCase  :     Tuple		=    relative_attention_num_buckets
   __UpperCAmelCase  :     Optional[int]		=    relative_attention_max_distance
   __UpperCAmelCase  :     Dict		=    dropout_rate
   __UpperCAmelCase  :     Union[str, Any]		=    layer_norm_epsilon
   __UpperCAmelCase  :     Tuple		=    initializer_factor
   __UpperCAmelCase  :     Union[str, Any]		=    feed_forward_proj
   __UpperCAmelCase  :     Optional[Any]		=    use_cache

   __UpperCAmelCase  :     Any		=    self.feed_forward_proj.split('-'       )
   __UpperCAmelCase  :     Dict		=    act_info[-1]
   __UpperCAmelCase  :     Any		=    act_info[0] == 'gated'

   if len(_UpperCAmelCase       ) > 1 and act_info[0] != "gated" or len(_UpperCAmelCase       ) > 2:
     raise ValueError(
         F"`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer."
         'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. '
         '\'gated-gelu\' or \'relu\''       )

   # for backwards compatibility
   if feed_forward_proj == "gated-gelu":
     __UpperCAmelCase  :     List[str]		=    'gelu_new'




 @property
 def 						a					( self       ):
   return self.d_model




 @property
 def 						a					( self       ):
   return self.num_heads




 @property
 def 						a					( self       ):
   return self.num_layers



class     lowerCamelCase_   ( _lowerCAmelCase):




 @property
 # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs
 def 						a					( self       ):
   __UpperCAmelCase  :     Optional[int]		=    {
       'input_ids': {0: 'batch', 1: 'encoder_sequence'},
       'attention_mask': {0: 'batch', 1: 'encoder_sequence'},
   }
   if self.use_past:
     __UpperCAmelCase  :     Optional[Any]		=    'past_encoder_sequence + sequence'
     __UpperCAmelCase  :     Tuple		=    {0: 'batch'}
     __UpperCAmelCase  :     List[Any]		=    {0: 'batch', 1: 'past_decoder_sequence + sequence'}
   else:
     __UpperCAmelCase  :     Tuple		=    {0: 'batch', 1: 'decoder_sequence'}
     __UpperCAmelCase  :     int		=    {0: 'batch', 1: 'decoder_sequence'}

   if self.use_past:
     self.fill_with_past_key_values_(_UpperCAmelCase     ,     direction='inputs'       )

   return common_inputs




 @property
 # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset
 def 						a					( self       ):
   return 13




 @property
 def 						a					( self       ):
   return 5E-4





