


'''simple docstring'''



import bza
import gzip
import lzma
import os
import shutil
import struct
import tarfile
import warnings
import zipfile
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Dict, List, Optional, Type, Union

from .. import config
from .filelock import FileLock
from .logging import get_logger


__lowercase	:						str       =	get_logger(__name__)





class 							__UpperCamelCase				:




	def __init__(   self						,				__a = None							):

						'''simple docstring'''





						__a			:       Dict					    =  (
						    os.path.join(__a						,				config.EXTRACTED_DATASETS_DIR							) if cache_dir else config.EXTRACTED_DATASETS_PATH
						)
						__a			:       Optional[int]					    =  Extractor




	def       __UpperCAmelCase							(   self						,				__a							):

						'''simple docstring'''





						from .file_utils import hash_url_to_filename

						# Path where we extract compressed archives
						# We extract in the cache dir, and get the extracted path name by hashing the original path"
						__a			:       List[str]					    =  os.path.abspath(__a							)
						return os.path.join(self.extract_dir						,				hash_url_to_filename(__a							)							)




	def       __UpperCAmelCase							(   self						,				__a						,				__a							):

						'''simple docstring'''





						return force_extract or (
						    not os.path.isfile(__a							) and not (os.path.isdir(__a							) and os.listdir(__a							))
						)





	def       __UpperCAmelCase							(   self						,				__a						,				__a = False							):

						'''simple docstring'''





						__a			:       Tuple					    =  self.extractor.infer_extractor_format(__a							)
						if not extractor_format:
											return input_path
						__a			:       Union[str, Any]					    =  self._get_output_path(__a							)
						if self._do_extract(__a						,				__a							):
											self.extractor.extract(__a						,				__a						,				__a							)
						return output_path





class 							__UpperCamelCase				(		lowerCAmelCase_					):




	@classmethod
	@abstractmethod
	def       __UpperCAmelCase							(   cls						,				__a						,				**__a							):

						'''simple docstring'''





						...





	@staticmethod
	@abstractmethod
	def       __UpperCAmelCase							(   __a						,				__a							):

						'''simple docstring'''





						...





class 							__UpperCamelCase				(		lowerCAmelCase_		,      lowerCAmelCase_					):
	A_				=    []




	@staticmethod
	def       __UpperCAmelCase							(   __a						,				__a							):

						'''simple docstring'''





						with open(__a						,				'rb'							) as f:
											return f.read(__a							)





	@classmethod
	def       __UpperCAmelCase							(   cls						,				__a						,				__a = b""							):

						'''simple docstring'''





						if not magic_number:
											__a			:       Dict					    =  max(len(__a							) for cls_magic_number in cls.magic_numbers							)
											try:
																__a			:       Any					    =  cls.read_magic_number(__a						,				__a							)
											except OSError:
																return False
						return any(magic_number.startswith(__a							) for cls_magic_number in cls.magic_numbers							)





class 							__UpperCamelCase				(		lowerCAmelCase_					):




	@classmethod
	def       __UpperCAmelCase							(   cls						,				__a						,				**__a							):

						'''simple docstring'''





						return tarfile.is_tarfile(__a							)




	@staticmethod
	def       __UpperCAmelCase							(   __a						,				__a							):

						'''simple docstring'''





						def resolved(__a							) -> str:
											return os.path.realpath(os.path.abspath(__a							)							)

						def badpath(__a						,				__a							) -> bool:
											# joinpath will ignore base if path is absolute
											return not resolved(os.path.join(__a						,				__a							)							).startswith(__a							)

						def badlink(__a						,				__a							) -> bool:
											# Links are interpreted relative to the directory containing the link
											__a			:       Optional[Any]					    =  resolved(os.path.join(__a						,				os.path.dirname(info.name							)							)							)
											return badpath(info.linkname						,				base=__a							)

						__a			:       List[str]					    =  resolved(__a							)

						for finfo in members:
											if badpath(finfo.name						,				__a							):
																logger.error(f"""Extraction of {finfo.name} is blocked (illegal path)"""							)
											elif finfo.issym() and badlink(__a						,				__a							):
																logger.error(f"""Extraction of {finfo.name} is blocked: Symlink to {finfo.linkname}"""							)
											elif finfo.islnk() and badlink(__a						,				__a							):
																logger.error(f"""Extraction of {finfo.name} is blocked: Hard link to {finfo.linkname}"""							)
											else:
																yield finfo





	@staticmethod
	def       __UpperCAmelCase							(   __a						,				__a							):

						'''simple docstring'''





						os.makedirs(__a						,				exist_ok=__a							)
						__a			:       int					    =  tarfile.open(__a							)
						tar_file.extractall(__a						,				members=TarExtractor.safemembers(__a						,				__a							)							)
						tar_file.close()





class 							__UpperCamelCase				(		lowerCAmelCase_					):
	A_				=    [B"\x1F\x8B"]




	@staticmethod
	def       __UpperCAmelCase							(   __a						,				__a							):

						'''simple docstring'''





						with gzip.open(__a						,				'rb'							) as gzip_file:
											with open(__a						,				'wb'							) as extracted_file:
																shutil.copyfileobj(__a						,				__a							)





class 							__UpperCamelCase				(		lowerCAmelCase_					):
	A_				=    [
	    B"PK\x03\x04",
	    B"PK\x05\x06",  # empty archive
	    B"PK\x07\x08",  # spanned archive
	]




	@classmethod
	def       __UpperCAmelCase							(   cls						,				__a						,				__a = b""							):

						'''simple docstring'''





						if super().is_extractable(__a						,				magic_number=__a							):
											return True
						try:
											# Alternative version of zipfile.is_zipfile that has less false positives, but misses executable zip archives.
											# From: https://github.com/python/cpython/pull/5053
											from zipfile import (
											    _CD_SIGNATURE,
											    _ECD_DISK_NUMBER,
											    _ECD_DISK_START,
											    _ECD_ENTRIES_TOTAL,
											    _ECD_OFFSET,
											    _ECD_SIZE,
											    _EndRecData,
											    sizeCentralDir,
											    stringCentralDir,
											    structCentralDir,
											)

											with open(__a						,				'rb'							) as fp:
																__a			:       Any					    =  _EndRecData(__a							)
																if endrec:
																					if endrec[_ECD_ENTRIES_TOTAL] == 0 and endrec[_ECD_SIZE] == 0 and endrec[_ECD_OFFSET] == 0:
																										return True  # Empty zipfiles are still zipfiles
																					elif endrec[_ECD_DISK_NUMBER] == endrec[_ECD_DISK_START]:
																										fp.seek(endrec[_ECD_OFFSET]							)  # Central directory is on the same disk
																										if fp.tell() == endrec[_ECD_OFFSET] and endrec[_ECD_SIZE] >= sizeCentralDir:
																															__a			:       Union[str, Any]					    =  fp.read(__a							)  # CD is where we expect it to be
																															if len(__a							) == sizeCentralDir:
																																				__a			:       List[str]					    =  struct.unpack(__a						,				__a							)  # CD is the right size
																																				if centdir[_CD_SIGNATURE] == stringCentralDir:
																																									return True  # First central directory entry  has correct magic number
											return False
						except Exception:  # catch all errors in case future python versions change the zipfile internals
											return False





	@staticmethod
	def       __UpperCAmelCase							(   __a						,				__a							):

						'''simple docstring'''





						os.makedirs(__a						,				exist_ok=__a							)
						with zipfile.ZipFile(__a						,				'r'							) as zip_file:
											zip_file.extractall(__a							)
											zip_file.close()





class 							__UpperCamelCase				(		lowerCAmelCase_					):
	A_				=    [B"\xFD\x37\x7A\x58\x5A\x00"]




	@staticmethod
	def       __UpperCAmelCase							(   __a						,				__a							):

						'''simple docstring'''





						with lzma.open(__a							) as compressed_file:
											with open(__a						,				'wb'							) as extracted_file:
																shutil.copyfileobj(__a						,				__a							)





class 							__UpperCamelCase				(		lowerCAmelCase_					):
	A_				=    [B"Rar!\x1a\x07\x00", B"Rar!\x1a\x07\x01\x00"]  # RAR_ID  # RAR5_ID




	@staticmethod
	def       __UpperCAmelCase							(   __a						,				__a							):

						'''simple docstring'''





						if not config.RARFILE_AVAILABLE:
											raise ImportError('Please pip install rarfile'							)
						import rarfile

						os.makedirs(__a						,				exist_ok=__a							)
						__a			:       Tuple					    =  rarfile.RarFile(__a							)
						rf.extractall(__a							)
						rf.close()





class 							__UpperCamelCase				(		lowerCAmelCase_					):
	A_				=    [B"\x28\xb5\x2F\xFD"]




	@staticmethod
	def       __UpperCAmelCase							(   __a						,				__a							):

						'''simple docstring'''





						if not config.ZSTANDARD_AVAILABLE:
											raise ImportError('Please pip install zstandard'							)
						import zstandard as zstd

						__a			:       Any					    =  zstd.ZstdDecompressor()
						with open(__a						,				'rb'							) as ifh, open(__a						,				'wb'							) as ofh:
											dctx.copy_stream(__a						,				__a							)





class 							__UpperCamelCase				(		lowerCAmelCase_					):
	A_				=    [B"\x42\x5A\x68"]




	@staticmethod
	def       __UpperCAmelCase							(   __a						,				__a							):

						'''simple docstring'''





						with bza.open(__a						,				'rb'							) as compressed_file:
											with open(__a						,				'wb'							) as extracted_file:
																shutil.copyfileobj(__a						,				__a							)





class 							__UpperCamelCase				(		lowerCAmelCase_					):
	A_				=    [B"\x37\x7A\xBC\xAF\x27\x1C"]




	@staticmethod
	def       __UpperCAmelCase							(   __a						,				__a							):

						'''simple docstring'''





						if not config.PY7ZR_AVAILABLE:
											raise ImportError('Please pip install py7zr'							)
						import pyazr

						os.makedirs(__a						,				exist_ok=__a							)
						with pyazr.SevenZipFile(__a						,				'r'							) as archive:
											archive.extractall(__a							)





class 							__UpperCamelCase				(		lowerCAmelCase_					):
	A_				=    [B"\x04\x22\x4D\x18"]




	@staticmethod
	def       __UpperCAmelCase							(   __a						,				__a							):

						'''simple docstring'''





						if not config.LZ4_AVAILABLE:
											raise ImportError('Please pip install lz4'							)
						import lza.frame

						with lza.frame.open(__a						,				'rb'							) as compressed_file:
											with open(__a						,				'wb'							) as extracted_file:
																shutil.copyfileobj(__a						,				__a							)





class 							__UpperCamelCase				:
	#  Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip)
	A_				=    {
	    "tar": TarExtractor,
	    "gzip": GzipExtractor,
	    "zip": ZipExtractor,
	    "xz": XzExtractor,
	    "rar": RarExtractor,
	    "zstd": ZstdExtractor,
	    "bz2": BzipaExtractor,
	    "7z": SevenZipExtractor,  # <Added version="2.4.0"/>
	    "lz4": LzaExtractor,  # <Added version="2.4.0"/>
	}




	@classmethod
	def       __UpperCAmelCase							(   cls							):

						'''simple docstring'''





						return max(
						    len(__a							)
						    for extractor in cls.extractors.values()
						    if issubclass(__a						,				__a							)
						    for extractor_magic_number in extractor.magic_numbers							)




	@staticmethod
	def       __UpperCAmelCase							(   __a						,				__a							):

						'''simple docstring'''





						try:
											return MagicNumberBaseExtractor.read_magic_number(__a						,				magic_number_length=__a							)
						except OSError:
											return b""




	@classmethod
	def       __UpperCAmelCase							(   cls						,				__a						,				__a = False							):

						'''simple docstring'''





						warnings.warn(
						    'Method \'is_extractable\' was deprecated in version 2.4.0 and will be removed in 3.0.0. '
						    'Use \'infer_extractor_format\' instead.'						,				category=__a						,				)
						__a			:       Tuple					    =  cls.infer_extractor_format(__a							)
						if extractor_format:
											return True if not return_extractor else (True, cls.extractors[extractor_format])
						return False if not return_extractor else (False, None)




	@classmethod
	def       __UpperCAmelCase							(   cls						,				__a							):  # <Added version="2.4.0"/>

						'''simple docstring'''





						__a			:       Dict					    =  cls._get_magic_number_max_length()
						__a			:       Dict					    =  cls._read_magic_number(__a						,				__a							)
						for extractor_format, extractor in cls.extractors.items():
											if extractor.is_extractable(__a						,				magic_number=__a							):
																return extractor_format





	@classmethod
	def       __UpperCAmelCase							(   cls						,				__a						,				__a						,				__a = None						,				__a = "deprecated"						,				):

						'''simple docstring'''





						os.makedirs(os.path.dirname(__a							)						,				exist_ok=__a							)
						# Prevent parallel extractions
						__a			:       Any					    =  str(Path(__a							).with_suffix('.lock'							)							)
						with FileLock(__a							):
											shutil.rmtree(__a						,				ignore_errors=__a							)
											if extractor_format or extractor != "deprecated":
																if extractor != "deprecated" or not isinstance(__a						,				__a							):  # passed as positional arg
																					warnings.warn(
																					    'Parameter \'extractor\' was deprecated in version 2.4.0 and will be removed in 3.0.0. '
																					    'Use \'extractor_format\' instead.'						,				category=__a						,				)
																					__a			:       Tuple					    =  extractor if extractor != 'deprecated' else extractor_format
																else:
																					__a			:       Union[str, Any]					    =  cls.extractors[extractor_format]
																return extractor.extract(__a						,				__a							)
											else:
																warnings.warn(
																    'Parameter \'extractor_format\' was made required in version 2.4.0 and not passing it will raise an '
																    'exception in 3.0.0.'						,				category=__a						,				)
																for extractor in cls.extractors.values():
																					if extractor.is_extractable(__a							):
																										return extractor.extract(__a						,				__a							)







'''simple docstring'''



from __future__ import annotations

import copy
import inspect
import unittest

import numpy as np

from transformers import is_tf_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_tf, slow
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
	import tensorflow as tf

	from transformers import (
	    TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
	    TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
	    TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
	    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
	    TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
	    LayoutLMvaConfig,
	    TFLayoutLMvaForQuestionAnswering,
	    TFLayoutLMvaForSequenceClassification,
	    TFLayoutLMvaForTokenClassification,
	    TFLayoutLMvaModel,
	)

if is_vision_available():
	from PIL import Image

	from transformers import LayoutLMvaImageProcessor





class 							__UpperCamelCase				:




	def __init__(   self						,				__a						,				__a=2						,				__a=3						,				__a=4						,				__a=2						,				__a=7						,				__a=True						,				__a=True						,				__a=True						,				__a=True						,				__a=99						,				__a=36						,				__a=2						,				__a=4						,				__a=37						,				__a="gelu"						,				__a=0.1						,				__a=0.1						,				__a=512						,				__a=16						,				__a=2						,				__a=0.02						,				__a=6						,				__a=6						,				__a=3						,				__a=4						,				__a=None						,				__a=1000						,				):

						'''simple docstring'''





						__a			:       Optional[Any]					    =  parent
						__a			:       int					    =  batch_size
						__a			:       Any					    =  num_channels
						__a			:       Optional[int]					    =  image_size
						__a			:       Dict					    =  patch_size
						__a			:       int					    =  is_training
						__a			:       Union[str, Any]					    =  use_input_mask
						__a			:       Optional[int]					    =  use_token_type_ids
						__a			:       Dict					    =  use_labels
						__a			:       str					    =  vocab_size
						__a			:       List[Any]					    =  hidden_size
						__a			:       Union[str, Any]					    =  num_hidden_layers
						__a			:       str					    =  num_attention_heads
						__a			:       Union[str, Any]					    =  intermediate_size
						__a			:       Any					    =  hidden_act
						__a			:       List[str]					    =  hidden_dropout_prob
						__a			:       List[str]					    =  attention_probs_dropout_prob
						__a			:       List[Any]					    =  max_position_embeddings
						__a			:       Tuple					    =  type_vocab_size
						__a			:       Any					    =  type_sequence_label_size
						__a			:       Optional[int]					    =  initializer_range
						__a			:       Any					    =  coordinate_size
						__a			:       List[Any]					    =  shape_size
						__a			:       Optional[int]					    =  num_labels
						__a			:       Dict					    =  num_choices
						__a			:       Union[str, Any]					    =  scope
						__a			:       Union[str, Any]					    =  range_bbox

						# LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
						__a			:       Optional[int]					    =  text_seq_length
						__a			:       Any					    =  (image_size // patch_size) ** 2 + 1
						__a			:       Dict					    =  self.text_seq_length + self.image_seq_length




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						__a			:       str					    =  ids_tensor([self.batch_size, self.text_seq_length]						,				self.vocab_size							)

						__a			:       Tuple					    =  ids_tensor([self.batch_size, self.text_seq_length, 4]						,				self.range_bbox							)
						__a			:       Any					    =  bbox.numpy()
						# Ensure that bbox is legal
						for i in range(bbox.shape[0]							):
											for j in range(bbox.shape[1]							):
																if bbox[i, j, 3] < bbox[i, j, 1]:
																					__a			:       List[Any]					    =  bbox[i, j, 3]
																					__a			:       Tuple					    =  bbox[i, j, 1]
																					__a			:       str					    =  tmp_coordinate
																if bbox[i, j, 2] < bbox[i, j, 0]:
																					__a			:       int					    =  bbox[i, j, 2]
																					__a			:       Dict					    =  bbox[i, j, 0]
																					__a			:       int					    =  tmp_coordinate
						__a			:       Optional[int]					    =  tf.constant(__a							)

						__a			:       Dict					    =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

						__a			:       str					    =  None
						if self.use_input_mask:
											__a			:       Optional[Any]					    =  random_attention_mask([self.batch_size, self.text_seq_length]							)

						__a			:       str					    =  None
						if self.use_token_type_ids:
											__a			:       List[Any]					    =  ids_tensor([self.batch_size, self.text_seq_length]						,				self.type_vocab_size							)

						__a			:       Optional[Any]					    =  None
						__a			:       Optional[int]					    =  None
						if self.use_labels:
											__a			:       List[Any]					    =  ids_tensor([self.batch_size]						,				self.type_sequence_label_size							)
											__a			:       Optional[int]					    =  ids_tensor([self.batch_size, self.text_seq_length]						,				self.num_labels							)

						__a			:       int					    =  LayoutLMvaConfig(
						    vocab_size=self.vocab_size						,				hidden_size=self.hidden_size						,				num_hidden_layers=self.num_hidden_layers						,				num_attention_heads=self.num_attention_heads						,				intermediate_size=self.intermediate_size						,				hidden_act=self.hidden_act						,				hidden_dropout_prob=self.hidden_dropout_prob						,				attention_probs_dropout_prob=self.attention_probs_dropout_prob						,				max_position_embeddings=self.max_position_embeddings						,				type_vocab_size=self.type_vocab_size						,				initializer_range=self.initializer_range						,				coordinate_size=self.coordinate_size						,				shape_size=self.shape_size						,				input_size=self.image_size						,				patch_size=self.patch_size						,				)

						return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels




	def       __UpperCAmelCase							(   self						,				__a						,				__a						,				__a						,				__a						,				__a						,				__a							):

						'''simple docstring'''





						__a			:       Dict					    =  TFLayoutLMvaModel(config=__a							)

						# text + image
						__a			:       List[Any]					    =  model(__a						,				pixel_values=__a						,				training=__a							)
						__a			:       Any					    =  model(
						    __a						,				bbox=__a						,				pixel_values=__a						,				attention_mask=__a						,				token_type_ids=__a						,				training=__a						,				)
						__a			:       Optional[int]					    =  model(__a						,				bbox=__a						,				pixel_values=__a						,				training=__a							)

						self.parent.assertEqual(result.last_hidden_state.shape						,				(self.batch_size, self.seq_length, self.hidden_size)							)

						# text only
						__a			:       Any					    =  model(__a						,				training=__a							)
						self.parent.assertEqual(
						    result.last_hidden_state.shape						,				(self.batch_size, self.text_seq_length, self.hidden_size)							)

						# image only
						__a			:       str					    =  model({'pixel_values': pixel_values}						,				training=__a							)
						self.parent.assertEqual(
						    result.last_hidden_state.shape						,				(self.batch_size, self.image_seq_length, self.hidden_size)							)




	def       __UpperCAmelCase							(   self						,				__a						,				__a						,				__a						,				__a						,				__a						,				__a						,				__a							):

						'''simple docstring'''





						__a			:       Any					    =  self.num_labels
						__a			:       Dict					    =  TFLayoutLMvaForSequenceClassification(config=__a							)
						__a			:       List[str]					    =  model(
						    __a						,				bbox=__a						,				pixel_values=__a						,				attention_mask=__a						,				token_type_ids=__a						,				labels=__a						,				training=__a						,				)
						self.parent.assertEqual(result.logits.shape						,				(self.batch_size, self.num_labels)							)




	def       __UpperCAmelCase							(   self						,				__a						,				__a						,				__a						,				__a						,				__a						,				__a						,				__a							):

						'''simple docstring'''





						__a			:       str					    =  self.num_labels
						__a			:       Optional[Any]					    =  TFLayoutLMvaForTokenClassification(config=__a							)
						__a			:       List[str]					    =  model(
						    __a						,				bbox=__a						,				pixel_values=__a						,				attention_mask=__a						,				token_type_ids=__a						,				labels=__a						,				training=__a						,				)
						self.parent.assertEqual(result.logits.shape						,				(self.batch_size, self.text_seq_length, self.num_labels)							)




	def       __UpperCAmelCase							(   self						,				__a						,				__a						,				__a						,				__a						,				__a						,				__a						,				__a							):

						'''simple docstring'''





						__a			:       List[Any]					    =  2
						__a			:       Any					    =  TFLayoutLMvaForQuestionAnswering(config=__a							)
						__a			:       Any					    =  model(
						    __a						,				bbox=__a						,				pixel_values=__a						,				attention_mask=__a						,				token_type_ids=__a						,				start_positions=__a						,				end_positions=__a						,				training=__a						,				)
						self.parent.assertEqual(result.start_logits.shape						,				(self.batch_size, self.seq_length)							)
						self.parent.assertEqual(result.end_logits.shape						,				(self.batch_size, self.seq_length)							)





	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						__a			:       Dict					    =  self.prepare_config_and_inputs()
						((__a)    ,				(__a)    ,				(__a)    ,				(__a)    ,				(__a)    ,				(__a)    ,				(__a)    ,				(__a))			:       Dict					    =  config_and_inputs
						__a			:       Any					    =  {
						    'input_ids': input_ids,
						    'bbox': bbox,
						    'pixel_values': pixel_values,
						    'token_type_ids': token_type_ids,
						    'attention_mask': input_mask,
						}
						return config, inputs_dict





@require_tf
class 							__UpperCamelCase				(		lowerCAmelCase_		,      lowerCAmelCase_		,      unittest.TestCase					):
	A_				=    (
	    (
	        TFLayoutLMvaModel,
	        TFLayoutLMvaForQuestionAnswering,
	        TFLayoutLMvaForSequenceClassification,
	        TFLayoutLMvaForTokenClassification,
	    )
	    if is_tf_available()
	    else ()
	)
	A_				=    (
	    {"document-question-answering": TFLayoutLMvaForQuestionAnswering, "feature-extraction": TFLayoutLMvaModel}
	    if is_tf_available()
	    else {}
	)

	A_				=    False
	A_				=    False
	A_				=    False




	def       __UpperCAmelCase							(   self						,				__a						,				__a						,				__a						,				__a						,				__a							):

						'''simple docstring'''





						return True




	def       __UpperCAmelCase							(   self						,				__a						,				__a						,				__a=False							):

						'''simple docstring'''





						__a			:       str					    =  copy.deepcopy(__a							)

						if model_class in get_values(__a							):
											__a			:       str					    =  {
											    k: tf.tile(tf.expand_dims(__a						,				1							)						,				(1, self.model_tester.num_choices) + (1,) * (v.ndim - 1)							)
											    if isinstance(__a						,				tf.Tensor							) and v.ndim > 0
											    else v
											    for k, v in inputs_dict.items()
											}

						if return_labels:
											if model_class in get_values(__a							):
																__a			:       Optional[int]					    =  tf.ones(self.model_tester.batch_size						,				dtype=tf.intaa							)
											elif model_class in get_values(__a							):
																__a			:       int					    =  tf.zeros(self.model_tester.batch_size						,				dtype=tf.intaa							)
																__a			:       Optional[Any]					    =  tf.zeros(self.model_tester.batch_size						,				dtype=tf.intaa							)
											elif model_class in get_values(__a							):
																__a			:       Any					    =  tf.zeros(self.model_tester.batch_size						,				dtype=tf.intaa							)
											elif model_class in get_values(__a							):
																__a			:       Union[str, Any]					    =  tf.zeros(
																    (self.model_tester.batch_size, self.model_tester.text_seq_length)						,				dtype=tf.intaa							)

						return inputs_dict




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						__a			:       Optional[Any]					    =  TFLayoutLMvaModelTester(self							)
						__a			:       Optional[int]					    =  ConfigTester(self						,				config_class=__a						,				hidden_size=37							)




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						self.config_tester.run_common_tests()




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						__a    ,				__a			:       Dict					    =  self.model_tester.prepare_config_and_inputs_for_common()
						for model_class in self.all_model_classes:
											__a			:       Dict					    =  model_class(__a							)
											if getattr(__a						,				'hf_compute_loss'						,				__a							):
																# The number of elements in the loss should be the same as the number of elements in the label
																__a			:       Union[str, Any]					    =  self._prepare_for_class(inputs_dict.copy()						,				__a						,				return_labels=__a							)
																__a			:       str					    =  prepared_for_class[
																    sorted(prepared_for_class.keys() - inputs_dict.keys()						,				reverse=__a							)[0]
																]
																__a			:       Dict					    =  added_label.shape.as_list()[:1]

																# Test that model correctly compute the loss with kwargs
																__a			:       int					    =  self._prepare_for_class(inputs_dict.copy()						,				__a						,				return_labels=__a							)
																__a			:       Dict					    =  prepared_for_class.pop('input_ids'							)

																__a			:       Tuple					    =  model(__a						,				**__a							)[0]
																self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]							)

																# Test that model correctly compute the loss when we mask some positions
																__a			:       int					    =  self._prepare_for_class(inputs_dict.copy()						,				__a						,				return_labels=__a							)
																__a			:       str					    =  prepared_for_class.pop('input_ids'							)
																if "labels" in prepared_for_class:
																					__a			:       Union[str, Any]					    =  prepared_for_class['labels'].numpy()
																					if len(labels.shape							) > 1 and labels.shape[1] != 1:
																										__a			:       List[Any]					    =  -100
																										__a			:       List[str]					    =  tf.convert_to_tensor(__a							)
																										__a			:       Any					    =  model(__a						,				**__a							)[0]
																										self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]							)
																										self.assertTrue(not np.any(np.isnan(loss.numpy()							)							)							)

                # Test that model correctly compute the loss with a dict
																__a			:       Union[str, Any]					    =  self._prepare_for_class(inputs_dict.copy()						,				__a						,				return_labels=__a							)
																__a			:       str					    =  model(__a							)[0]
																self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]							)

																# Test that model correctly compute the loss with a tuple
																__a			:       Tuple					    =  self._prepare_for_class(inputs_dict.copy()						,				__a						,				return_labels=__a							)

																# Get keys that were added with the _prepare_for_class function
																__a			:       Dict					    =  prepared_for_class.keys() - inputs_dict.keys()
																__a			:       Any					    =  inspect.signature(model.call							).parameters
																__a			:       str					    =  list(signature.keys()							)

																# Create a dictionary holding the location of the tensors in the tuple
																__a			:       List[Any]					    =  {0: 'input_ids'}
																for label_key in label_keys:
																					__a			:       List[Any]					    =  signature_names.index(__a							)
																					__a			:       Union[str, Any]					    =  label_key
																__a			:       List[str]					    =  sorted(tuple_index_mapping.items()							)
																# Initialize a list with their default values, update the values and convert to a tuple
																__a			:       Union[str, Any]					    =  []

																for name in signature_names:
																					if name != "kwargs":
																										list_input.append(signature[name].default							)

																for index, value in sorted_tuple_index_mapping:
																					__a			:       Optional[Any]					    =  prepared_for_class[value]

																__a			:       str					    =  tuple(__a							)

																# Send to model
																__a			:       Tuple					    =  model(tuple_input[:-1]							)[0]

																self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]							)




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						(
						    (
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				
						)			:       Optional[int]					    =  self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(__a						,				__a						,				__a						,				__a						,				__a						,				__a							)




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						(
						    (
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				
						)			:       Dict					    =  self.model_tester.prepare_config_and_inputs()
						for type in ["absolute", "relative_key", "relative_key_query"]:
											__a			:       Any					    =  type
											self.model_tester.create_and_check_model(__a						,				__a						,				__a						,				__a						,				__a						,				__a							)




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						(
						    (
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				
						)			:       List[str]					    =  self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_sequence_classification(
						    __a						,				__a						,				__a						,				__a						,				__a						,				__a						,				__a							)




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						(
						    (
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				
						)			:       Optional[Any]					    =  self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_token_classification(
						    __a						,				__a						,				__a						,				__a						,				__a						,				__a						,				__a							)




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						(
						    (
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				(
						    __a
						)    ,				
						)			:       int					    =  self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_question_answering(
						    __a						,				__a						,				__a						,				__a						,				__a						,				__a						,				__a							)





	@slow
	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											__a			:       List[Any]					    =  TFLayoutLMvaModel.from_pretrained(__a							)
											self.assertIsNotNone(__a							)






def   lowerCamelCase							():
					__a			:       Optional[Any]					    =  Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'   )
					return image





@require_tf
class 							__UpperCamelCase				(		unittest.TestCase					):




	@cached_property
	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						return LayoutLMvaImageProcessor(apply_ocr=__a							) if is_vision_available() else None





	@slow
	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						__a			:       str					    =  TFLayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base'							)

						__a			:       Tuple					    =  self.default_image_processor
						__a			:       List[Any]					    =  prepare_img()
						__a			:       int					    =  image_processor(images=__a						,				return_tensors='tf'							).pixel_values

						__a			:       Union[str, Any]					    =  tf.constant([[1, 2]]							)
						__a			:       Optional[Any]					    =  tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]]							)						,				axis=0							)

						# forward pass
						__a			:       Tuple					    =  model(input_ids=__a						,				bbox=__a						,				pixel_values=__a						,				training=__a							)

						# verify the logits
						__a			:       List[Any]					    =  (1, 199, 768)
						self.assertEqual(outputs.last_hidden_state.shape						,				__a							)

						__a			:       Optional[Any]					    =  tf.constant(
						    [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]]							)

						self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3]						,				__a						,				atol=1E-4							)							)



