





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__    :      List[Any]       					=10_00

class    __A  :


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

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

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


				def _snake_case							(		self ,			UpperCAmelCase_ ,			UpperCAmelCase_=None				):
								if color is None:
												lowerCamelCase									=self.edgecolor
								((lowerCamelCase)			,	(lowerCamelCase)			,	(lowerCamelCase)			,	(lowerCamelCase))									=box
								lowerCamelCase									=xa - xa
								lowerCamelCase									=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 _snake_case							(		self ,			UpperCAmelCase_ ,			UpperCAmelCase_=None ,			UpperCAmelCase_=None ,			UpperCAmelCase_=None ,			UpperCAmelCase_=None				):
								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(UpperCAmelCase_ ,			torch.Tensor				):
												lowerCamelCase									=boxes.numpy()
								if isinstance(UpperCAmelCase_ ,			UpperCAmelCase_				):
												lowerCamelCase									=np.array(UpperCAmelCase_				)
								assert isinstance(UpperCAmelCase_ ,			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(UpperCAmelCase_				)				)]
								lowerCamelCase									=[assigned_colors[idx] for idx in sorted_idxs]
								if obj_ids is not None:
												lowerCamelCase									=self._create_text_labels_attr(UpperCAmelCase_ ,			UpperCAmelCase_ ,			UpperCAmelCase_ ,			UpperCAmelCase_				)
												for i in range(len(UpperCAmelCase_				)				):
																lowerCamelCase									=assigned_colors[i]
																self.add_box(boxes[i] ,			UpperCAmelCase_				)
																self.draw_labels(labels[i] ,			boxes[i] ,			UpperCAmelCase_				)


				def _snake_case							(		self ,			UpperCAmelCase_ ,			UpperCAmelCase_ ,			UpperCAmelCase_				):
								lowerCamelCase			,	lowerCamelCase			,	lowerCamelCase			,	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(UpperCAmelCase_ ,			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=UpperCAmelCase_ ,			position=UpperCAmelCase_ ,			color=UpperCAmelCase_ ,			)


				def _snake_case							(		self ,			UpperCAmelCase_ ,			UpperCAmelCase_ ,			UpperCAmelCase_="g" ,			UpperCAmelCase_="left" ,			):
								lowerCamelCase									=0
								lowerCamelCase									=self.font_size
								lowerCamelCase									=np.maximum(list(mplc.to_rgb(UpperCAmelCase_				)				) ,			0.2				)
								lowerCamelCase									=max(0.8 ,			np.max(UpperCAmelCase_				)				)
								lowerCamelCase									={
								    """facecolor""": """black""",
								    """alpha""": self.alpha,
								    """pad""": self.pad,
								    """edgecolor""": """none""",
								}
								lowerCamelCase			,	lowerCamelCase									=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 _snake_case							(		self ,			UpperCAmelCase_=None				):
								if saveas is None:
												lowerCamelCase									=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 _snake_case							(		self ,			UpperCAmelCase_ ,			UpperCAmelCase_ ,			UpperCAmelCase_ ,			UpperCAmelCase_				):
								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(UpperCAmelCase_ ,			UpperCAmelCase_ ,			UpperCAmelCase_ ,			UpperCAmelCase_				)
								]
								return labels


				def _snake_case							(		self ,			UpperCAmelCase_ ,			UpperCAmelCase_				):
								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(UpperCAmelCase_ ,			s * 100				) for li, s in zip(UpperCAmelCase_ ,			UpperCAmelCase_				)]
								return labels


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


				def _snake_case							(		self				):
								if not self.pynb:
												lowerCamelCase			,	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(UpperCAmelCase_				)
												lowerCamelCase			,	lowerCamelCase									=self.width, self.height
												lowerCamelCase									=buf.getvalue()
												lowerCamelCase									=self.img

								lowerCamelCase									=np.frombuffer(UpperCAmelCase_ ,			dtype="""uint8"""				)
								lowerCamelCase									=buffer.reshape(UpperCAmelCase_ ,			UpperCAmelCase_ ,			4				)
								lowerCamelCase			,	lowerCamelCase									=np.split(UpperCAmelCase_ ,			[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 _snake_case							(		self ,			UpperCAmelCase_ ,			UpperCAmelCase_				):
								assert brightness_factor >= -1.0 and brightness_factor <= 1.0
								lowerCamelCase									=mplc.to_rgb(UpperCAmelCase_				)
								lowerCamelCase									=colorsys.rgb_to_hls(*mplc.to_rgb(UpperCAmelCase_				)				)
								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] ,			UpperCAmelCase_ ,			polygon_color[2]				)
								return modified_color




UpperCAmelCase__    :      Dict       					=(
    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)
)












import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_layoutlm import LayoutLMTokenizer


UpperCAmelCase__    :      int       					=logging.get_logger(__name__)

UpperCAmelCase__    :      Optional[Any]       					={'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''}

UpperCAmelCase__    :      List[str]       					={
    '''vocab_file''': {
        '''microsoft/layoutlm-base-uncased''': (
            '''https://huggingface.co/microsoft/layoutlm-base-uncased/resolve/main/vocab.txt'''
        ),
        '''microsoft/layoutlm-large-uncased''': (
            '''https://huggingface.co/microsoft/layoutlm-large-uncased/resolve/main/vocab.txt'''
        ),
    },
    '''tokenizer_file''': {
        '''microsoft/layoutlm-base-uncased''': (
            '''https://huggingface.co/microsoft/layoutlm-base-uncased/resolve/main/tokenizer.json'''
        ),
        '''microsoft/layoutlm-large-uncased''': (
            '''https://huggingface.co/microsoft/layoutlm-large-uncased/resolve/main/tokenizer.json'''
        ),
    },
}

UpperCAmelCase__    :      Dict       					={
    '''microsoft/layoutlm-base-uncased''': 5_12,
    '''microsoft/layoutlm-large-uncased''': 5_12,
}

UpperCAmelCase__    :      List[Any]       					={
    '''microsoft/layoutlm-base-uncased''': {'''do_lower_case''': True},
    '''microsoft/layoutlm-large-uncased''': {'''do_lower_case''': True},
}

class    __A  (    a     ):
				__A  =					VOCAB_FILES_NAMES
				__A  =					PRETRAINED_VOCAB_FILES_MAP
				__A  =					PRETRAINED_INIT_CONFIGURATION
				__A  =					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
				__A  =					LayoutLMTokenizer


				def __init__(		self ,			UpperCAmelCase_=None ,			UpperCAmelCase_=None ,			UpperCAmelCase_=True ,			UpperCAmelCase_="[UNK]" ,			UpperCAmelCase_="[SEP]" ,			UpperCAmelCase_="[PAD]" ,			UpperCAmelCase_="[CLS]" ,			UpperCAmelCase_="[MASK]" ,			UpperCAmelCase_=True ,			UpperCAmelCase_=None ,			**UpperCAmelCase_ ,			):
								super().__init__(
								    UpperCAmelCase_ ,			tokenizer_file=UpperCAmelCase_ ,			do_lower_case=UpperCAmelCase_ ,			unk_token=UpperCAmelCase_ ,			sep_token=UpperCAmelCase_ ,			pad_token=UpperCAmelCase_ ,			cls_token=UpperCAmelCase_ ,			mask_token=UpperCAmelCase_ ,			tokenize_chinese_chars=UpperCAmelCase_ ,			strip_accents=UpperCAmelCase_ ,			**UpperCAmelCase_ ,			)

								lowerCamelCase									=json.loads(self.backend_tokenizer.normalizer.__getstate__()				)
								if (
								    normalizer_state.get("""lowercase""" ,			UpperCAmelCase_				) != do_lower_case
								    or normalizer_state.get("""strip_accents""" ,			UpperCAmelCase_				) != strip_accents
								    or normalizer_state.get("""handle_chinese_chars""" ,			UpperCAmelCase_				) != tokenize_chinese_chars
								):
												lowerCamelCase									=getattr(UpperCAmelCase_ ,			normalizer_state.pop("""type"""				)				)
												lowerCamelCase									=do_lower_case
												lowerCamelCase									=strip_accents
												lowerCamelCase									=tokenize_chinese_chars
												lowerCamelCase									=normalizer_class(**UpperCAmelCase_				)

								lowerCamelCase									=do_lower_case


				def _snake_case							(		self ,			UpperCAmelCase_ ,			UpperCAmelCase_=None				):
								lowerCamelCase									=[self.cls_token_id] + token_ids_a + [self.sep_token_id]

								if token_ids_a:
												output += token_ids_a + [self.sep_token_id]

								return output


				def _snake_case							(		self ,			UpperCAmelCase_ ,			UpperCAmelCase_ = None				):
								lowerCamelCase									=[self.sep_token_id]
								lowerCamelCase									=[self.cls_token_id]
								if token_ids_a is None:
												return len(cls + token_ids_a + sep				) * [0]
								return len(cls + token_ids_a + sep				) * [0] + len(token_ids_a + sep				) * [1]


				def _snake_case							(		self ,			UpperCAmelCase_ ,			UpperCAmelCase_ = None				):
								lowerCamelCase									=self._tokenizer.model.save(UpperCAmelCase_ ,			name=UpperCAmelCase_				)
								return tuple(UpperCAmelCase_				)





