

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							:     int,		__A							:     Any,		__A							:     str=2,		__A							:     str=3,		__A							:     Tuple=4,		__A							:     List[Any]=2,		__A							:     int=7,		__A							:     Dict=True,		__A							:     List[Any]=True,		__A							:     Tuple=True,		__A							:     Union[str, Any]=True,		__A							:     Dict=9_9,		__A							:     List[str]=3_6,		__A							:     Optional[Any]=2,		__A							:     int=4,		__A							:     Optional[Any]=3_7,		__A							:     List[str]="gelu",		__A							:     Dict=0.1,		__A							:     Any=0.1,		__A							:     int=5_1_2,		__A							:     str=1_6,		__A							:     str=2,		__A							:     Any=0.0_2,		__A							:     str=6,		__A							:     str=6,		__A							:     Any=3,		__A							:     List[Any]=4,		__A							:     Dict=None,		__A							:     List[Any]=1_0_0_0,		):
     UpperCAmelCase       :							Union[str, Any]  = parent
     UpperCAmelCase       :							Any  = batch_size
     UpperCAmelCase       :							int  = num_channels
     UpperCAmelCase       :							int  = image_size
     UpperCAmelCase       :							str  = patch_size
     UpperCAmelCase       :							Dict  = is_training
     UpperCAmelCase       :							Union[str, Any]  = use_input_mask
     UpperCAmelCase       :							Optional[int]  = use_token_type_ids
     UpperCAmelCase       :							int  = use_labels
     UpperCAmelCase       :							List[str]  = vocab_size
     UpperCAmelCase       :							Dict  = hidden_size
     UpperCAmelCase       :							Optional[Any]  = num_hidden_layers
     UpperCAmelCase       :							Any  = num_attention_heads
     UpperCAmelCase       :							str  = intermediate_size
     UpperCAmelCase       :							str  = hidden_act
     UpperCAmelCase       :							Optional[int]  = hidden_dropout_prob
     UpperCAmelCase       :							Optional[Any]  = attention_probs_dropout_prob
     UpperCAmelCase       :							Any  = max_position_embeddings
     UpperCAmelCase       :							List[Any]  = type_vocab_size
     UpperCAmelCase       :							List[str]  = type_sequence_label_size
     UpperCAmelCase       :							int  = initializer_range
     UpperCAmelCase       :							Optional[Any]  = coordinate_size
     UpperCAmelCase       :							Tuple  = shape_size
     UpperCAmelCase       :							int  = num_labels
     UpperCAmelCase       :							List[str]  = num_choices
     UpperCAmelCase       :							str  = scope
     UpperCAmelCase       :							List[Any]  = range_bbox

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



   def        __magic_name__    (							self							:     Optional[int]						):
     UpperCAmelCase       :							Dict  = ids_tensor([self.batch_size, self.text_seq_length],		self.vocab_size						)

     UpperCAmelCase       :							Any  = ids_tensor([self.batch_size, self.text_seq_length, 4],		self.range_bbox						)
     UpperCAmelCase       :							str  = 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]:
           UpperCAmelCase       :							Dict  = bbox[i, j, 3]
           UpperCAmelCase       :							str  = bbox[i, j, 1]
           UpperCAmelCase       :							List[str]  = tmp_coordinate
         if bbox[i, j, 2] < bbox[i, j, 0]:
           UpperCAmelCase       :							List[str]  = bbox[i, j, 2]
           UpperCAmelCase       :							int  = bbox[i, j, 0]
           UpperCAmelCase       :							int  = tmp_coordinate
     UpperCAmelCase       :							Tuple  = tf.constant(__UpperCAmelCase						)

     UpperCAmelCase       :							Tuple  = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

     UpperCAmelCase       :							Tuple  = None
     if self.use_input_mask:
       UpperCAmelCase       :							str  = random_attention_mask([self.batch_size, self.text_seq_length]						)

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

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

     UpperCAmelCase       :							Optional[Any]  = 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        __magic_name__    (							self							:     int,		__A							:     Optional[Any],		__A							:     Dict,		__A							:     str,		__A							:     Optional[Any],		__A							:     Union[str, Any],		__A							:     Optional[Any]						):
     UpperCAmelCase       :							Optional[int]  = TFLayoutLMvaModel(config=__UpperCAmelCase						)

     # text + image
     UpperCAmelCase       :							str  = model(__UpperCAmelCase,		pixel_values=__UpperCAmelCase,		training=__UpperCAmelCase						)
     UpperCAmelCase       :							int  = model(
         __UpperCAmelCase,		bbox=__UpperCAmelCase,		pixel_values=__UpperCAmelCase,		attention_mask=__UpperCAmelCase,		token_type_ids=__UpperCAmelCase,		training=__UpperCAmelCase,		)
     UpperCAmelCase       :							Tuple  = model(__UpperCAmelCase,		bbox=__UpperCAmelCase,		pixel_values=__UpperCAmelCase,		training=__UpperCAmelCase						)

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

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

     # image only
     UpperCAmelCase       :							Optional[Any]  = model({'''pixel_values''': pixel_values},		training=__UpperCAmelCase						)
     self.parent.assertEqual(
         result.last_hidden_state.shape,		(self.batch_size, self.image_seq_length, self.hidden_size)						)



   def        __magic_name__    (							self							:     List[Any],		__A							:     str,		__A							:     Optional[Any],		__A							:     List[Any],		__A							:     Optional[int],		__A							:     List[str],		__A							:     Dict,		__A							:     List[Any]						):
     UpperCAmelCase       :							str  = self.num_labels
     UpperCAmelCase       :							Union[str, Any]  = TFLayoutLMvaForSequenceClassification(config=__UpperCAmelCase						)
     UpperCAmelCase       :							Any  = model(
         __UpperCAmelCase,		bbox=__UpperCAmelCase,		pixel_values=__UpperCAmelCase,		attention_mask=__UpperCAmelCase,		token_type_ids=__UpperCAmelCase,		labels=__UpperCAmelCase,		training=__UpperCAmelCase,		)
     self.parent.assertEqual(result.logits.shape,		(self.batch_size, self.num_labels)						)



   def        __magic_name__    (							self							:     Optional[Any],		__A							:     Optional[Any],		__A							:     str,		__A							:     Optional[Any],		__A							:     Union[str, Any],		__A							:     Dict,		__A							:     int,		__A							:     Union[str, Any]						):
     UpperCAmelCase       :							Union[str, Any]  = self.num_labels
     UpperCAmelCase       :							Tuple  = TFLayoutLMvaForTokenClassification(config=__UpperCAmelCase						)
     UpperCAmelCase       :							Optional[int]  = model(
         __UpperCAmelCase,		bbox=__UpperCAmelCase,		pixel_values=__UpperCAmelCase,		attention_mask=__UpperCAmelCase,		token_type_ids=__UpperCAmelCase,		labels=__UpperCAmelCase,		training=__UpperCAmelCase,		)
     self.parent.assertEqual(result.logits.shape,		(self.batch_size, self.text_seq_length, self.num_labels)						)



   def        __magic_name__    (							self							:     str,		__A							:     Optional[Any],		__A							:     Tuple,		__A							:     List[Any],		__A							:     List[Any],		__A							:     List[str],		__A							:     Optional[int],		__A							:     Optional[Any]						):
     UpperCAmelCase       :							Dict  = 2
     UpperCAmelCase       :							Optional[Any]  = TFLayoutLMvaForQuestionAnswering(config=__UpperCAmelCase						)
     UpperCAmelCase       :							Dict  = model(
         __UpperCAmelCase,		bbox=__UpperCAmelCase,		pixel_values=__UpperCAmelCase,		attention_mask=__UpperCAmelCase,		token_type_ids=__UpperCAmelCase,		start_positions=__UpperCAmelCase,		end_positions=__UpperCAmelCase,		training=__UpperCAmelCase,		)
     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        __magic_name__    (							self							:     Tuple						):
     UpperCAmelCase       :							List[Any]  = self.prepare_config_and_inputs()
     ((UpperCAmelCase) ,						(UpperCAmelCase) ,						(UpperCAmelCase) ,						(UpperCAmelCase) ,						(UpperCAmelCase) ,						(UpperCAmelCase) ,						(UpperCAmelCase) ,						(UpperCAmelCase))       :							Optional[Any]  = config_and_inputs
     UpperCAmelCase       :							Dict  = {
         '''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     (       UpperCAmelCase_			,  UpperCAmelCase_			,  unittest.TestCase						):
   UpperCamelCase        =     (
       (
           TFLayoutLMvaModel,
           TFLayoutLMvaForQuestionAnswering,
           TFLayoutLMvaForSequenceClassification,
           TFLayoutLMvaForTokenClassification,
       )
       if is_tf_available()
       else ()
   )
   UpperCamelCase        =     (
       {'document-question-answering': TFLayoutLMvaForQuestionAnswering, 'feature-extraction': TFLayoutLMvaModel}
       if is_tf_available()
       else {}
   )

   UpperCamelCase        =     False
   UpperCamelCase        =     False
   UpperCamelCase        =     False



   def        __magic_name__    (							self							:     int,		__A							:     Any,		__A							:     Tuple,		__A							:     int,		__A							:     Optional[Any],		__A							:     int						):
     return True



   def        __magic_name__    (							self							:     str,		__A							:     Union[str, Any],		__A							:     Optional[Any],		__A							:     List[str]=False						):
     UpperCAmelCase       :							int  = copy.deepcopy(__UpperCAmelCase						)

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

     if return_labels:
       if model_class in get_values(__UpperCAmelCase						):
         UpperCAmelCase       :							Dict  = tf.ones(self.model_tester.batch_size,		dtype=tf.intaa						)
       elif model_class in get_values(__UpperCAmelCase						):
         UpperCAmelCase       :							List[str]  = tf.zeros(self.model_tester.batch_size,		dtype=tf.intaa						)
         UpperCAmelCase       :							str  = tf.zeros(self.model_tester.batch_size,		dtype=tf.intaa						)
       elif model_class in get_values(__UpperCAmelCase						):
         UpperCAmelCase       :							str  = tf.zeros(self.model_tester.batch_size,		dtype=tf.intaa						)
       elif model_class in get_values(__UpperCAmelCase						):
         UpperCAmelCase       :							Dict  = tf.zeros(
             (self.model_tester.batch_size, self.model_tester.text_seq_length),		dtype=tf.intaa						)

     return inputs_dict



   def        __magic_name__    (							self							:     int						):
     UpperCAmelCase       :							Dict  = TFLayoutLMvaModelTester(self						)
     UpperCAmelCase       :							Optional[int]  = ConfigTester(self,		config_class=__UpperCAmelCase,		hidden_size=3_7						)



   def        __magic_name__    (							self							:     Tuple						):
     self.config_tester.run_common_tests()



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

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

         UpperCAmelCase       :							Union[str, Any]  = model(__UpperCAmelCase,		**__UpperCAmelCase						)[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
         UpperCAmelCase       :							Union[str, Any]  = self._prepare_for_class(inputs_dict.copy(),		__UpperCAmelCase,		return_labels=__UpperCAmelCase						)
         UpperCAmelCase       :							str  = prepared_for_class.pop('''input_ids'''						)
         if "labels" in prepared_for_class:
           UpperCAmelCase       :							Any  = prepared_for_class['''labels'''].numpy()
           if len(labels.shape						) > 1 and labels.shape[1] != 1:
             UpperCAmelCase       :							str  = -1_0_0
             UpperCAmelCase       :							Union[str, Any]  = tf.convert_to_tensor(__UpperCAmelCase						)
             UpperCAmelCase       :							int  = model(__UpperCAmelCase,		**__UpperCAmelCase						)[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
         UpperCAmelCase       :							Dict  = self._prepare_for_class(inputs_dict.copy(),		__UpperCAmelCase,		return_labels=__UpperCAmelCase						)
         UpperCAmelCase       :							int  = model(__UpperCAmelCase						)[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
         UpperCAmelCase       :							Optional[Any]  = self._prepare_for_class(inputs_dict.copy(),		__UpperCAmelCase,		return_labels=__UpperCAmelCase						)

         # Get keys that were added with the _prepare_for_class function
         UpperCAmelCase       :							Tuple  = prepared_for_class.keys() - inputs_dict.keys()
         UpperCAmelCase       :							List[str]  = inspect.signature(model.call						).parameters
         UpperCAmelCase       :							Tuple  = list(signature.keys()						)

         # Create a dictionary holding the location of the tensors in the tuple
         UpperCAmelCase       :							Tuple  = {0: '''input_ids'''}
         for label_key in label_keys:
           UpperCAmelCase       :							str  = signature_names.index(__UpperCAmelCase						)
           UpperCAmelCase       :							List[str]  = label_key
         UpperCAmelCase       :							Dict  = sorted(tuple_index_mapping.items()						)
         # Initialize a list with their default values, update the values and convert to a tuple
         UpperCAmelCase       :							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:
           UpperCAmelCase       :							Tuple  = prepared_for_class[value]

         UpperCAmelCase       :							int  = tuple(__UpperCAmelCase						)

         # Send to model
         UpperCAmelCase       :							Union[str, Any]  = model(tuple_input[:-1]						)[0]

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



   def        __magic_name__    (							self							:     Optional[int]						):
     (
         (
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						      
     )       :							Any  = self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(__UpperCAmelCase,		__UpperCAmelCase,		__UpperCAmelCase,		__UpperCAmelCase,		__UpperCAmelCase,		__UpperCAmelCase						)



   def        __magic_name__    (							self							:     Union[str, Any]						):
     (
         (
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						      
     )       :							str  = self.model_tester.prepare_config_and_inputs()
     for type in ["absolute", "relative_key", "relative_key_query"]:
       UpperCAmelCase       :							Tuple  = type
       self.model_tester.create_and_check_model(__UpperCAmelCase,		__UpperCAmelCase,		__UpperCAmelCase,		__UpperCAmelCase,		__UpperCAmelCase,		__UpperCAmelCase						)



   def        __magic_name__    (							self							:     Optional[int]						):
     (
         (
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						      
     )       :							List[str]  = self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_sequence_classification(
         __UpperCAmelCase,		__UpperCAmelCase,		__UpperCAmelCase,		__UpperCAmelCase,		__UpperCAmelCase,		__UpperCAmelCase,		__UpperCAmelCase						)



   def        __magic_name__    (							self							:     List[Any]						):
     (
         (
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						      
     )       :							List[str]  = self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_token_classification(
         __UpperCAmelCase,		__UpperCAmelCase,		__UpperCAmelCase,		__UpperCAmelCase,		__UpperCAmelCase,		__UpperCAmelCase,		__UpperCAmelCase						)



   def        __magic_name__    (							self							:     int						):
     (
         (
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						(
         UpperCAmelCase      
     ) ,						      
     )       :							Dict  = self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_question_answering(
         __UpperCAmelCase,		__UpperCAmelCase,		__UpperCAmelCase,		__UpperCAmelCase,		__UpperCAmelCase,		__UpperCAmelCase,		__UpperCAmelCase						)





   @slow
   def        __magic_name__    (							self							:     Any						):



     for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       UpperCAmelCase       :							Union[str, Any]  = TFLayoutLMvaModel.from_pretrained(__UpperCAmelCase						)
       self.assertIsNotNone(__UpperCAmelCase						)






def 			a__     (		)  ->						int:
  UpperCAmelCase       :							Any  = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''			)
  return image






@require_tf
class 					__UpperCAmelCase     (       unittest.TestCase						):



   @cached_property
   def        __magic_name__    (							self							:     int						):
     return LayoutLMvaImageProcessor(apply_ocr=__UpperCAmelCase						) if is_vision_available() else None





   @slow
   def        __magic_name__    (							self							:     Tuple						):
     UpperCAmelCase       :							Optional[Any]  = TFLayoutLMvaModel.from_pretrained('''microsoft/layoutlmv3-base'''						)

     UpperCAmelCase       :							Dict  = self.default_image_processor
     UpperCAmelCase       :							List[Any]  = prepare_img()
     UpperCAmelCase       :							Any  = image_processor(images=__UpperCAmelCase,		return_tensors='''tf'''						).pixel_values

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

     # forward pass
     UpperCAmelCase       :							Optional[Any]  = model(input_ids=__UpperCAmelCase,		bbox=__UpperCAmelCase,		pixel_values=__UpperCAmelCase,		training=__UpperCAmelCase						)

     # verify the logits
     UpperCAmelCase       :							int  = (1, 1_9_9, 7_6_8)
     self.assertEqual(outputs.last_hidden_state.shape,		__UpperCAmelCase						)

     UpperCAmelCase       :							Tuple  = tf.constant(
         [[-0.0_5_2_9, 0.3_6_1_8, 0.1_6_3_2], [-0.1_5_8_7, -0.1_6_6_7, -0.0_4_0_0], [-0.1_5_5_7, -0.1_6_7_1, -0.0_5_0_5]]						)

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






import os
import tempfile
import unittest

from transformers.models.marian.convert_marian_tatoeba_to_pytorch import DEFAULT_REPO, TatoebaConverter
from transformers.testing_utils import slow
from transformers.utils import cached_property





@unittest.skipUnless(os.path.exists(UpperCAmelCase_     )		,				'Tatoeba directory does not exist.'     )
class      A							(				unittest.TestCase     ):


   @cached_property
   def 			lowercase_      (self     :						Optional[int]		)						->				List[Any]:
         """simple docstring"""



         UpperCAmelCase__								=  tempfile.mkdtemp()
         return TatoebaConverter(save_dir=__UpperCAmelCase		)


   @slow
   def 			lowercase_      (self     :						List[Any]		)						->				Optional[int]:
         """simple docstring"""



         self.resolver.convert_models(["heb-eng"]		)





   @slow
   def 			lowercase_      (self     :						Dict		)						->				List[str]:
         """simple docstring"""



         UpperCAmelCase__		,      UpperCAmelCase__								=  self.resolver.write_model_card("opus-mt-he-en"       ,  dry_run=__UpperCAmelCase		)
         assert mmeta["long_pair"] == "heb-eng"



