
"""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


SCREAMING_SNAKE_CASE_  					= 1000






class      __a      :







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

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

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







       def  _snake_case      (       self				,lowerCamelCase_				,lowerCamelCase_=None		):



          '''simple docstring'''

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







       def  _snake_case      (       self				,lowerCamelCase_				,lowerCamelCase_=None				,lowerCamelCase_=None				,lowerCamelCase_=None				,lowerCamelCase_=None		):



          '''simple docstring'''

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

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







       def  _snake_case      (       self				,lowerCamelCase_				,lowerCamelCase_				,lowerCamelCase_		):



          '''simple docstring'''

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

          _UpperCAmelCase 						=       (ya - ya) / np.sqrt(self.height * self.width		)
          _UpperCAmelCase 						=       self._change_color_brightness(SCREAMING_SNAKE_CASE__				,brightness_factor=0.7		)
          _UpperCAmelCase 						=       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=SCREAMING_SNAKE_CASE__				,position=SCREAMING_SNAKE_CASE__				,color=SCREAMING_SNAKE_CASE__				,)







       def  _snake_case      (       self				,lowerCamelCase_				,lowerCamelCase_				,lowerCamelCase_="g"				,lowerCamelCase_="left"				,):



          '''simple docstring'''

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







       def  _snake_case      (       self				,lowerCamelCase_=None		):



          '''simple docstring'''

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







       def  _snake_case      (       self				,lowerCamelCase_				,lowerCamelCase_				,lowerCamelCase_				,lowerCamelCase_		):



          '''simple docstring'''

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







       def  _snake_case      (       self				,lowerCamelCase_				,lowerCamelCase_		):



          '''simple docstring'''

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







       def  _snake_case      (       self				,lowerCamelCase_=255		):



          '''simple docstring'''

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







       def  _snake_case      (       self		):



          '''simple docstring'''

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

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

          try:
             import numexpr as ne  # fuse them with numexpr

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

          return visualized_image.astype("uint8"		)







       def  _snake_case      (       self				,lowerCamelCase_				,lowerCamelCase_		):



          '''simple docstring'''

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



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




"""simple docstring"""




import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_splinter import SplinterTokenizer


SCREAMING_SNAKE_CASE_  :      str							=      logging.get_logger(__name__)

SCREAMING_SNAKE_CASE_  :      List[Any]							=      {'''vocab_file''': '''vocab.txt'''}

SCREAMING_SNAKE_CASE_  :      int							=      {
    '''vocab_file''': {
        '''tau/splinter-base''': '''https://huggingface.co/tau/splinter-base/resolve/main/vocab.txt''',
        '''tau/splinter-base-qass''': '''https://huggingface.co/tau/splinter-base-qass/resolve/main/vocab.txt''',
        '''tau/splinter-large''': '''https://huggingface.co/tau/splinter-large/resolve/main/vocab.txt''',
        '''tau/splinter-large-qass''': '''https://huggingface.co/tau/splinter-large-qass/resolve/main/vocab.txt''',
    }
}

SCREAMING_SNAKE_CASE_  :      Union[str, Any]							=      {
    '''tau/splinter-base''': 512,
    '''tau/splinter-base-qass''': 512,
    '''tau/splinter-large''': 512,
    '''tau/splinter-large-qass''': 512,
}

SCREAMING_SNAKE_CASE_  :      List[Any]							=      {
    '''tau/splinter-base''': {'''do_lower_case''': False},
    '''tau/splinter-base-qass''': {'''do_lower_case''': False},
    '''tau/splinter-large''': {'''do_lower_case''': False},
    '''tau/splinter-large-qass''': {'''do_lower_case''': False},
}


class 		_A							(      __a       ):
      __a             =						VOCAB_FILES_NAMES
      __a             =						PRETRAINED_VOCAB_FILES_MAP
      __a             =						PRETRAINED_INIT_CONFIGURATION
      __a             =						PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      __a             =						SplinterTokenizer





      def __init__(	self     ,    SCREAMING_SNAKE_CASE__=None     ,    SCREAMING_SNAKE_CASE__=None     ,    SCREAMING_SNAKE_CASE__=True     ,    SCREAMING_SNAKE_CASE__="[UNK]"     ,    SCREAMING_SNAKE_CASE__="[SEP]"     ,    SCREAMING_SNAKE_CASE__="[PAD]"     ,    SCREAMING_SNAKE_CASE__="[CLS]"     ,    SCREAMING_SNAKE_CASE__="[MASK]"     ,    SCREAMING_SNAKE_CASE__="[QUESTION]"     ,    SCREAMING_SNAKE_CASE__=True     ,    SCREAMING_SNAKE_CASE__=None     ,    **SCREAMING_SNAKE_CASE__     ,    ) ->       Optional[Any]:
         super().__init__(
             SCREAMING_SNAKE_CASE__     ,    tokenizer_file=SCREAMING_SNAKE_CASE__     ,    do_lower_case=SCREAMING_SNAKE_CASE__     ,    unk_token=SCREAMING_SNAKE_CASE__     ,    sep_token=SCREAMING_SNAKE_CASE__     ,    pad_token=SCREAMING_SNAKE_CASE__     ,    cls_token=SCREAMING_SNAKE_CASE__     ,    mask_token=SCREAMING_SNAKE_CASE__     ,    tokenize_chinese_chars=SCREAMING_SNAKE_CASE__     ,    strip_accents=SCREAMING_SNAKE_CASE__     ,    additional_special_tokens=(question_token,)     ,    **SCREAMING_SNAKE_CASE__     ,    )

         lowerCamelCase__						       =      json.loads(self.backend_tokenizer.normalizer.__getstate__()		)
         if (
             pre_tok_state.get("lowercase"     ,    SCREAMING_SNAKE_CASE__		) != do_lower_case
             or pre_tok_state.get("strip_accents"     ,    SCREAMING_SNAKE_CASE__		) != strip_accents
         ):
            lowerCamelCase__						       =      getattr(SCREAMING_SNAKE_CASE__     ,    pre_tok_state.pop("type"		)		)
            lowerCamelCase__						       =      do_lower_case
            lowerCamelCase__						       =      strip_accents
            lowerCamelCase__						       =      pre_tok_class(**SCREAMING_SNAKE_CASE__		)

         lowerCamelCase__						       =      do_lower_case





      @property
      def        _lowerCamelCase	(	self		) ->       Optional[Any]:
         return self.convert_tokens_to_ids(self.question_token		)





      def        _lowerCamelCase	(	self     ,    SCREAMING_SNAKE_CASE__     ,    SCREAMING_SNAKE_CASE__ = None		) ->       List[int]:
         if token_ids_a is None:
            return [self.cls_token_id] + token_ids_a + [self.sep_token_id]

         lowerCamelCase__						       =      [self.cls_token_id]
         lowerCamelCase__						       =      [self.sep_token_id]
         lowerCamelCase__						       =      [self.question_token_id] + [self.convert_tokens_to_ids("."		)]
         if self.padding_side == "right":
            # Input is question-then-context
            return cls + token_ids_a + question_suffix + sep + token_ids_a + sep
         else:
            # Input is context-then-question
            return cls + token_ids_a + sep + token_ids_a + question_suffix + sep





      def        _lowerCamelCase	(	self     ,    SCREAMING_SNAKE_CASE__     ,    SCREAMING_SNAKE_CASE__ = None		) ->       List[int]:
         lowerCamelCase__						       =      [self.sep_token_id]
         lowerCamelCase__						       =      [self.cls_token_id]
         lowerCamelCase__						       =      [self.question_token_id] + [self.convert_tokens_to_ids("."		)]
         if token_ids_a is None:
            return len(cls + token_ids_a + sep		) * [0]

         if self.padding_side == "right":
            # Input is question-then-context
            return len(cls + token_ids_a + question_suffix + sep		) * [0] + len(token_ids_a + sep		) * [1]
         else:
            # Input is context-then-question
            return len(cls + token_ids_a + sep		) * [0] + len(token_ids_a + question_suffix + sep		) * [1]





      def        _lowerCamelCase	(	self     ,    SCREAMING_SNAKE_CASE__     ,    SCREAMING_SNAKE_CASE__ = None		) ->       Tuple[str]:
         lowerCamelCase__						       =      self._tokenizer.model.save(SCREAMING_SNAKE_CASE__     ,    name=SCREAMING_SNAKE_CASE__		)
         return tuple(SCREAMING_SNAKE_CASE__		)




