






"""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  :  int   =			1_000




class  lowerCAmelCase__ :
   def __init__(		self			:  Optional[Any]       , snake_case__			:  Any       , snake_case__			:  Union[str, Any]=1.2       , snake_case__			:  str="g"       , snake_case__			:  Tuple=0.5       , snake_case__			:  str="-"       , snake_case__			:  str="test_out.jpg"       , snake_case__			:  List[str]=True       , snake_case__			:  Optional[Any]=False       , snake_case__			:  Dict=None       , snake_case__			:  Union[str, Any]=None       , snake_case__			:  Any=0.7       , ):


        '''simple docstring'''
        if isinstance(snake_case__       , torch.Tensor       ):
             UpperCAmelCase__	:						Tuple       =       img.numpy().astype("np.uint8"       )
        if isinstance(snake_case__       , snake_case__       ):
             UpperCAmelCase__	:						List[Any]       =       img_tensorize(snake_case__       )
        assert isinstance(snake_case__       , np.ndarray       )

        UpperCAmelCase__       ,							UpperCAmelCase__	:						Union[str, Any]       =       img.shape[1], img.shape[0]
        UpperCAmelCase__	:						Tuple       =       mplfigure.Figure(frameon=snake_case__       )
        UpperCAmelCase__	:						Any       =       fig.get_dpi()
        UpperCAmelCase__	:						Any       =       (width * scale + 1e-2) / dpi
        UpperCAmelCase__	:						Tuple       =       (height * scale + 1e-2) / dpi
        fig.set_size_inches(snake_case__       , snake_case__       )
        UpperCAmelCase__	:						Optional[int]       =       fig.add_axes([0.0, 0.0, 1.0, 1.0]       )
        ax.axis("off"       )
        ax.set_xlim(0.0       , snake_case__       )
        ax.set_ylim(snake_case__       )

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


        '''simple docstring'''
        if color is None:
             UpperCAmelCase__	:						Optional[Any]       =       self.edgecolor
        ((UpperCAmelCase__)       ,							(UpperCAmelCase__)       ,							(UpperCAmelCase__)       ,							(UpperCAmelCase__))	:						Dict       =       box
        UpperCAmelCase__	:						str       =       xa - xa
        UpperCAmelCase__	:						Optional[Any]       =       ya - ya
        self.ax.add_patch(
            mpl.patches.Rectangle(
                (xa, ya)       , snake_case__       , snake_case__       , fill=snake_case__       , edgecolor=snake_case__       , linewidth=self.font_size // 3       , alpha=self.alpha       , linestyle=self.linestyle       , )       )
   def 			__a       (		self			:  List[Any]       , snake_case__			:  List[Any]       , snake_case__			:  Optional[Any]=None       , snake_case__			:  Any=None       , snake_case__			:  Optional[int]=None       , snake_case__			:  Any=None       ):


        '''simple docstring'''
        if len(boxes.shape       ) > 2:
             UpperCAmelCase__	:						str       =       boxes[0]
        if len(obj_ids.shape       ) > 1:
             UpperCAmelCase__	:						List[str]       =       obj_ids[0]
        if len(obj_scores.shape       ) > 1:
             UpperCAmelCase__	:						str       =       obj_scores[0]
        if len(attr_ids.shape       ) > 1:
             UpperCAmelCase__	:						int       =       attr_ids[0]
        if len(attr_scores.shape       ) > 1:
             UpperCAmelCase__	:						Optional[int]       =       attr_scores[0]
        if isinstance(snake_case__       , torch.Tensor       ):
             UpperCAmelCase__	:						str       =       boxes.numpy()
        if isinstance(snake_case__       , snake_case__       ):
             UpperCAmelCase__	:						str       =       np.array(snake_case__       )
        assert isinstance(snake_case__       , np.ndarray       )
        UpperCAmelCase__	:						Optional[int]       =       np.prod(boxes[:, 2:] - boxes[:, :2]       , axis=1       )
        UpperCAmelCase__	:						Union[str, Any]       =       np.argsort(-areas       ).tolist()
        UpperCAmelCase__	:						Optional[Any]       =       boxes[sorted_idxs] if boxes is not None else None
        UpperCAmelCase__	:						Tuple       =       obj_ids[sorted_idxs] if obj_ids is not None else None
        UpperCAmelCase__	:						Optional[Any]       =       obj_scores[sorted_idxs] if obj_scores is not None else None
        UpperCAmelCase__	:						Optional[Any]       =       attr_ids[sorted_idxs] if attr_ids is not None else None
        UpperCAmelCase__	:						Tuple       =       attr_scores[sorted_idxs] if attr_scores is not None else None

        UpperCAmelCase__	:						int       =       [self._random_color(maximum=1       ) for _ in range(len(snake_case__       )       )]
        UpperCAmelCase__	:						List[str]       =       [assigned_colors[idx] for idx in sorted_idxs]
        if obj_ids is not None:
             UpperCAmelCase__	:						Tuple       =       self._create_text_labels_attr(snake_case__       , snake_case__       , snake_case__       , snake_case__       )
             for i in range(len(snake_case__       )       ):
                  UpperCAmelCase__	:						List[Any]       =       assigned_colors[i]
                  self.add_box(boxes[i]       , snake_case__       )
                  self.draw_labels(labels[i]       , boxes[i]       , snake_case__       )
   def 			__a       (		self			:  str       , snake_case__			:  str       , snake_case__			:  str       , snake_case__			:  Dict       ):


        '''simple docstring'''
        UpperCAmelCase__       ,							UpperCAmelCase__       ,							UpperCAmelCase__       ,							UpperCAmelCase__	:						Optional[Any]       =       box
        UpperCAmelCase__	:						List[str]       =       (xa, ya)
        UpperCAmelCase__	:						Optional[int]       =       (ya - ya) * (xa - xa)
        UpperCAmelCase__	:						Union[str, Any]       =       _SMALL_OBJ * self.scale
        if instance_area < small or ya - ya < 4_0 * self.scale:
             if ya >= self.height - 5:
                  UpperCAmelCase__	:						List[Any]       =       (xa, ya)
             else:
                  UpperCAmelCase__	:						Dict       =       (xa, ya)

        UpperCAmelCase__	:						Tuple       =       (ya - ya) / np.sqrt(self.height * self.width       )
        UpperCAmelCase__	:						Optional[int]       =       self._change_color_brightness(snake_case__       , brightness_factor=0.7       )
        UpperCAmelCase__	:						List[Any]       =       np.clip((height_ratio - 0.02) / 0.08 + 1       , 1.2       , 2       )
        font_size *= 0.75 * self.font_size

        self.draw_text(
            text=snake_case__       , position=snake_case__       , color=snake_case__       , )
   def 			__a       (		self			:  List[Any]       , snake_case__			:  Any       , snake_case__			:  str       , snake_case__			:  List[Any]="g"       , snake_case__			:  int="left"       , ):


        '''simple docstring'''
        UpperCAmelCase__	:						Dict       =       0
        UpperCAmelCase__	:						Dict       =       self.font_size
        UpperCAmelCase__	:						Optional[int]       =       np.maximum(list(mplc.to_rgb(snake_case__       )       )       , 0.2       )
        UpperCAmelCase__	:						Union[str, Any]       =       max(0.8       , np.max(snake_case__       )       )
        UpperCAmelCase__	:						List[Any]       =       {
            "facecolor": "black",
            "alpha": self.alpha,
            "pad": self.pad,
            "edgecolor": "none",
        }
        UpperCAmelCase__       ,							UpperCAmelCase__	:						str       =       position
        self.ax.text(
            snake_case__       , snake_case__       , snake_case__       , size=font_size * self.scale       , family="sans-serif"       , bbox=snake_case__       , verticalalignment="top"       , horizontalalignment=snake_case__       , color=snake_case__       , zorder=1_0       , rotation=snake_case__       , )
   def 			__a       (		self			:  List[Any]       , snake_case__			:  List[Any]=None       ):


        '''simple docstring'''
        if saveas is None:
             UpperCAmelCase__	:						str       =       self.saveas
        if saveas.lower().endswith(".jpg"       ) or saveas.lower().endswith(".png"       ):
             cva.imwrite(
                 snake_case__       , self._get_buffer()[:, :, ::-1]       , )
        else:
             self.fig.savefig(snake_case__       )
   def 			__a       (		self			:  Dict       , snake_case__			:  List[Any]       , snake_case__			:  Tuple       , snake_case__			:  Union[str, Any]       , snake_case__			:  int       ):


        '''simple docstring'''
        UpperCAmelCase__	:						Optional[int]       =       [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(snake_case__       , snake_case__       , snake_case__       , snake_case__       )
        ]
        return labels
   def 			__a       (		self			:  Union[str, Any]       , snake_case__			:  str       , snake_case__			:  Optional[Any]       ):


        '''simple docstring'''
        UpperCAmelCase__	:						int       =       [self.idaobj[i] for i in classes]
        if scores is not None:
             if labels is None:
                  UpperCAmelCase__	:						List[Any]       =       ["{:.0f}%".format(s * 1_0_0       ) for s in scores]
             else:
                  UpperCAmelCase__	:						int       =       ["{} {:.0f}%".format(snake_case__       , s * 1_0_0       ) for li, s in zip(snake_case__       , snake_case__       )]
        return labels
   def 			__a       (		self			:  Union[str, Any]       , snake_case__			:  Optional[Any]=2_5_5       ):


        '''simple docstring'''
        UpperCAmelCase__	:						Optional[Any]       =       np.random.randint(0       , len(_COLORS       )       )
        UpperCAmelCase__	:						List[str]       =       _COLORS[idx] * maximum
        if not self.rgb:
             UpperCAmelCase__	:						Optional[Any]       =       ret[::-1]
        return ret
   def 			__a       (		self			:  str       ):


        '''simple docstring'''
        if not self.pynb:
             UpperCAmelCase__       ,							UpperCAmelCase__	:						Tuple       =       self.canvas.print_to_buffer()
             if (width, height) != (self.width, self.height):
                  UpperCAmelCase__	:						Tuple       =       cva.resize(self.img       , (width, height)       )
             else:
                  UpperCAmelCase__	:						int       =       self.img
        else:
             UpperCAmelCase__	:						Union[str, Any]       =       io.BytesIO()  # works for cairo backend
             self.canvas.print_rgba(snake_case__       )
             UpperCAmelCase__       ,							UpperCAmelCase__	:						List[Any]       =       self.width, self.height
             UpperCAmelCase__	:						int       =       buf.getvalue()
             UpperCAmelCase__	:						Any       =       self.img

        UpperCAmelCase__	:						Tuple       =       np.frombuffer(snake_case__       , dtype="uint8"       )
        UpperCAmelCase__	:						List[str]       =       buffer.reshape(snake_case__       , snake_case__       , 4       )
        UpperCAmelCase__       ,							UpperCAmelCase__	:						Union[str, Any]       =       np.split(snake_case__       , [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__	:						List[str]       =       alpha.astype("float32"       ) / 255.0
             UpperCAmelCase__	:						Any       =       img * (1 - alpha) + rgb * alpha

        return visualized_image.astype("uint8"       )




   def 			__a       (		self			:  Optional[Any]       , snake_case__			:  str       , snake_case__			:  Optional[Any]       ):


        '''simple docstring'''
        assert brightness_factor >= -1.0 and brightness_factor <= 1.0
        UpperCAmelCase__	:						Any       =       mplc.to_rgb(snake_case__       )
        UpperCAmelCase__	:						List[Any]       =       colorsys.rgb_to_hls(*mplc.to_rgb(snake_case__       )       )
        UpperCAmelCase__	:						Tuple       =       polygon_color[1] + (brightness_factor * polygon_color[1])
        UpperCAmelCase__	:						Union[str, Any]       =       0.0 if modified_lightness < 0.0 else modified_lightness
        UpperCAmelCase__	:						str       =       1.0 if modified_lightness > 1.0 else modified_lightness
        UpperCAmelCase__	:						Any       =       colorsys.hls_to_rgb(polygon_color[0]       , snake_case__       , polygon_color[2]       )
        return modified_color




_lowerCAmelCase  :  Optional[Any]   =			(
    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_tokenizers_available, is_torch_available


_lowerCAmelCase  :  List[Any]   =			{
    """configuration_markuplm""": ["""MARKUPLM_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MarkupLMConfig"""],
    """feature_extraction_markuplm""": ["""MarkupLMFeatureExtractor"""],
    """processing_markuplm""": ["""MarkupLMProcessor"""],
    """tokenization_markuplm""": ["""MarkupLMTokenizer"""],
}

try:
 if not is_tokenizers_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 _lowerCAmelCase  :  str   =			["""MarkupLMTokenizerFast"""]

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 _lowerCAmelCase  :  List[str]   =			[
     """MARKUPLM_PRETRAINED_MODEL_ARCHIVE_LIST""",
     """MarkupLMForQuestionAnswering""",
     """MarkupLMForSequenceClassification""",
     """MarkupLMForTokenClassification""",
     """MarkupLMModel""",
     """MarkupLMPreTrainedModel""",
 ]


if TYPE_CHECKING:
 from .configuration_markuplm import MARKUPLM_PRETRAINED_CONFIG_ARCHIVE_MAP, MarkupLMConfig
 from .feature_extraction_markuplm import MarkupLMFeatureExtractor
 from .processing_markuplm import MarkupLMProcessor
 from .tokenization_markuplm import MarkupLMTokenizer

 try:
  if not is_tokenizers_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .tokenization_markuplm_fast import MarkupLMTokenizerFast

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_markuplm import (
      MARKUPLM_PRETRAINED_MODEL_ARCHIVE_LIST,
      MarkupLMForQuestionAnswering,
      MarkupLMForSequenceClassification,
      MarkupLMForTokenClassification,
      MarkupLMModel,
      MarkupLMPreTrainedModel,
  )


else:
 import sys

 _lowerCAmelCase  :  Dict   =			_LazyModule(__name__, globals()["""__file__"""], _import_structure)


