






"""simple docstring"""
from typing import Optional, Tuple, Union

import tensorflow as tf

from ...activations_tf import ACTaFN
from ...modeling_tf_outputs import (
    TFBaseModelOutputWithNoAttention,
    TFBaseModelOutputWithPoolingAndNoAttention,
    TFImageClassifierOutputWithNoAttention,
)
from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs
from ...tf_utils import shape_list
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_resnet import ResNetConfig


A_			: List[str]				=			logging.get_logger(__name__)

# General docstring
A_			: Any				=			"ResNetConfig"

# Base docstring
A_			: Union[str, Any]				=			"microsoft/resnet-50"
A_			: List[str]				=			[1, 20_48, 7, 7]

# Image classification docstring
A_			: int				=			"microsoft/resnet-50"
A_			: List[str]				=			"tiger cat"

A_			: int				=			[
    "microsoft/resnet-50",
    # See all resnet models at https://huggingface.co/models?filter=resnet
]



class 		a_      (	tf.keras.layers.Layer ):







      '''simple docstring'''

      def __init__(self,     lowerCamelCase_,     lowerCamelCase_ = 3,     lowerCamelCase_ = 1,     lowerCamelCase_ = "relu",     **lowerCamelCase_					):

       '''simple docstring'''



       super().__init__(**lowerCamelCase_					)
       lowerCamelCase__     :			int     				=						kernel_size // 2
       lowerCamelCase__     :			int     				=						tf.keras.layers.ConvaD(
           lowerCamelCase_,     kernel_size=lowerCamelCase_,     strides=lowerCamelCase_,     padding='valid',     use_bias=lowerCamelCase_,     name='convolution'					)
       # Use same default momentum and epsilon as PyTorch equivalent
       lowerCamelCase__     :			Union[str, Any]     				=						tf.keras.layers.BatchNormalization(epsilon=1e-5,     momentum=0.9,     name='normalization'					)
       lowerCamelCase__     :			List[Any]     				=						ACTaFN[activation] if activation is not None else tf.keras.layers.Activation('linear'					)




      def 			a__							(self,     lowerCamelCase_					):

       '''simple docstring'''



       lowerCamelCase__     :			Dict     				=						(self.pad_value, self.pad_value)
       lowerCamelCase__     :			Any     				=						tf.pad(lowerCamelCase_,     [(0, 0), height_pad, width_pad, (0, 0)]					)
       lowerCamelCase__     :			Optional[Any]     				=						self.conv(lowerCamelCase_					)
       return hidden_state





      def 			a__							(self,     lowerCamelCase_,     lowerCamelCase_ = False					):

       '''simple docstring'''



       lowerCamelCase__     :			Dict     				=						self.convolution(lowerCamelCase_					)
       lowerCamelCase__     :			int     				=						self.normalization(lowerCamelCase_,     training=lowerCamelCase_					)
       lowerCamelCase__     :			str     				=						self.activation(lowerCamelCase_					)
       return hidden_state



class 		a_      (	tf.keras.layers.Layer ):







      '''simple docstring'''

      def __init__(self,     lowerCamelCase_,     **lowerCamelCase_					):

       '''simple docstring'''



       super().__init__(**lowerCamelCase_					)
       lowerCamelCase__     :			Any     				=						TFResNetConvLayer(
           config.embedding_size,     kernel_size=7,     stride=2,     activation=config.hidden_act,     name='embedder',     )
       lowerCamelCase__     :			str     				=						tf.keras.layers.MaxPoolaD(pool_size=3,     strides=2,     padding='valid',     name='pooler'					)
       lowerCamelCase__     :			Any     				=						config.num_channels





      def 			a__							(self,     lowerCamelCase_,     lowerCamelCase_ = False					):

       '''simple docstring'''



       lowerCamelCase__				,     lowerCamelCase__				,     lowerCamelCase__				,     lowerCamelCase__     :			Dict     				=						shape_list(lowerCamelCase_					)
       if tf.executing_eagerly() and num_channels != self.num_channels:
        raise ValueError(
            'Make sure that the channel dimension of the pixel values match with the one set in the configuration.'					)
       lowerCamelCase__     :			int     				=						pixel_values
       lowerCamelCase__     :			Any     				=						self.embedder(lowerCamelCase_					)
       lowerCamelCase__     :			Optional[int]     				=						tf.pad(lowerCamelCase_,     [[0, 0], [1, 1], [1, 1], [0, 0]]					)
       lowerCamelCase__     :			Optional[Any]     				=						self.pooler(lowerCamelCase_					)
       return hidden_state



class 		a_      (	tf.keras.layers.Layer ):







      '''simple docstring'''

      def __init__(self,     lowerCamelCase_,     lowerCamelCase_ = 2,     **lowerCamelCase_					):

       '''simple docstring'''



       super().__init__(**lowerCamelCase_					)
       lowerCamelCase__     :			Union[str, Any]     				=						tf.keras.layers.ConvaD(
           lowerCamelCase_,     kernel_size=1,     strides=lowerCamelCase_,     use_bias=lowerCamelCase_,     name='convolution'					)
       # Use same default momentum and epsilon as PyTorch equivalent
       lowerCamelCase__     :			int     				=						tf.keras.layers.BatchNormalization(epsilon=1e-5,     momentum=0.9,     name='normalization'					)





      def 			a__							(self,     lowerCamelCase_,     lowerCamelCase_ = False					):

       '''simple docstring'''



       lowerCamelCase__     :			Any     				=						x
       lowerCamelCase__     :			Optional[Any]     				=						self.convolution(lowerCamelCase_					)
       lowerCamelCase__     :			Union[str, Any]     				=						self.normalization(lowerCamelCase_,     training=lowerCamelCase_					)
       return hidden_state



class 		a_      (	tf.keras.layers.Layer ):







      '''simple docstring'''

      def __init__(self,     lowerCamelCase_,     lowerCamelCase_,     lowerCamelCase_ = 1,     lowerCamelCase_ = "relu",     **lowerCamelCase_					):

       '''simple docstring'''



       super().__init__(**lowerCamelCase_					)
       lowerCamelCase__     :			Tuple     				=						in_channels != out_channels or stride != 1
       lowerCamelCase__     :			Optional[Any]     				=						TFResNetConvLayer(lowerCamelCase_,     stride=lowerCamelCase_,     name='layer.0'					)
       lowerCamelCase__     :			List[Any]     				=						TFResNetConvLayer(lowerCamelCase_,     activation=lowerCamelCase_,     name='layer.1'					)
       lowerCamelCase__     :			Optional[Any]     				=						(
           TFResNetShortCut(lowerCamelCase_,     stride=lowerCamelCase_,     name='shortcut'					)
           if should_apply_shortcut
           else tf.keras.layers.Activation('linear',     name='shortcut'					)
       )
       lowerCamelCase__     :			int     				=						ACTaFN[activation]





      def 			a__							(self,     lowerCamelCase_,     lowerCamelCase_ = False					):

       '''simple docstring'''



       lowerCamelCase__     :			List[str]     				=						hidden_state
       lowerCamelCase__     :			int     				=						self.conva(lowerCamelCase_,     training=lowerCamelCase_					)
       lowerCamelCase__     :			Dict     				=						self.conva(lowerCamelCase_,     training=lowerCamelCase_					)
       lowerCamelCase__     :			Dict     				=						self.shortcut(lowerCamelCase_,     training=lowerCamelCase_					)
       hidden_state += residual
       lowerCamelCase__     :			str     				=						self.activation(lowerCamelCase_					)
       return hidden_state



class 		a_      (	tf.keras.layers.Layer ):







      '''simple docstring'''

      def __init__(self,     lowerCamelCase_,     lowerCamelCase_,     lowerCamelCase_ = 1,     lowerCamelCase_ = "relu",     lowerCamelCase_ = 4,     **lowerCamelCase_,     ):

       '''simple docstring'''



       super().__init__(**lowerCamelCase_					)
       lowerCamelCase__     :			int     				=						in_channels != out_channels or stride != 1
       lowerCamelCase__     :			Optional[int]     				=						out_channels // reduction
       lowerCamelCase__     :			str     				=						TFResNetConvLayer(lowerCamelCase_,     kernel_size=1,     name='layer.0'					)
       lowerCamelCase__     :			Optional[int]     				=						TFResNetConvLayer(lowerCamelCase_,     stride=lowerCamelCase_,     name='layer.1'					)
       lowerCamelCase__     :			Optional[Any]     				=						TFResNetConvLayer(lowerCamelCase_,     kernel_size=1,     activation=lowerCamelCase_,     name='layer.2'					)
       lowerCamelCase__     :			Union[str, Any]     				=						(
           TFResNetShortCut(lowerCamelCase_,     stride=lowerCamelCase_,     name='shortcut'					)
           if should_apply_shortcut
           else tf.keras.layers.Activation('linear',     name='shortcut'					)
       )
       lowerCamelCase__     :			str     				=						ACTaFN[activation]





      def 			a__							(self,     lowerCamelCase_,     lowerCamelCase_ = False					):

       '''simple docstring'''



       lowerCamelCase__     :			Optional[Any]     				=						hidden_state
       lowerCamelCase__     :			Optional[Any]     				=						self.conva(lowerCamelCase_,     training=lowerCamelCase_					)
       lowerCamelCase__     :			Tuple     				=						self.conva(lowerCamelCase_,     training=lowerCamelCase_					)
       lowerCamelCase__     :			Union[str, Any]     				=						self.conva(lowerCamelCase_,     training=lowerCamelCase_					)
       lowerCamelCase__     :			Any     				=						self.shortcut(lowerCamelCase_,     training=lowerCamelCase_					)
       hidden_state += residual
       lowerCamelCase__     :			Optional[int]     				=						self.activation(lowerCamelCase_					)
       return hidden_state



class 		a_      (	tf.keras.layers.Layer ):







      '''simple docstring'''

      def __init__(self,     lowerCamelCase_,     lowerCamelCase_,     lowerCamelCase_,     lowerCamelCase_ = 2,     lowerCamelCase_ = 2,     **lowerCamelCase_					):

       '''simple docstring'''



       super().__init__(**lowerCamelCase_					)

       lowerCamelCase__     :			Any     				=						TFResNetBottleNeckLayer if config.layer_type == 'bottleneck' else TFResNetBasicLayer

       lowerCamelCase__     :			str     				=						[layer(lowerCamelCase_,     lowerCamelCase_,     stride=lowerCamelCase_,     activation=config.hidden_act,     name='layers.0'					)]
       layers += [
           layer(lowerCamelCase_,     lowerCamelCase_,     activation=config.hidden_act,     name=f'''layers.{i + 1}'''					)
           for i in range(depth - 1					)
       ]
       lowerCamelCase__     :			int     				=						layers





      def 			a__							(self,     lowerCamelCase_,     lowerCamelCase_ = False					):

       '''simple docstring'''



       for layer in self.stage_layers:
        lowerCamelCase__     :			List[str]     				=						layer(lowerCamelCase_,     training=lowerCamelCase_					)
       return hidden_state



class 		a_      (	tf.keras.layers.Layer ):







      '''simple docstring'''

      def __init__(self,     lowerCamelCase_,     **lowerCamelCase_					):

       '''simple docstring'''



       super().__init__(**lowerCamelCase_					)
       # based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input
       lowerCamelCase__     :			Dict     				=						[
           TFResNetStage(
               lowerCamelCase_,     config.embedding_size,     config.hidden_sizes[0],     stride=2 if config.downsample_in_first_stage else 1,     depth=config.depths[0],     name='stages.0',     )
       ]
       for i, (in_channels, out_channels, depth) in enumerate(
           zip(config.hidden_sizes,     config.hidden_sizes[1:],     config.depths[1:]					)					):
        self.stages.append(TFResNetStage(lowerCamelCase_,     lowerCamelCase_,     lowerCamelCase_,     depth=lowerCamelCase_,     name=f'''stages.{i + 1}'''					)					)





      def 			a__							(self,     lowerCamelCase_,     lowerCamelCase_ = False,     lowerCamelCase_ = True,     lowerCamelCase_ = False,     ):

       '''simple docstring'''



       lowerCamelCase__     :			int     				=						() if output_hidden_states else None

       for stage_module in self.stages:
        if output_hidden_states:
         lowerCamelCase__     :			Optional[Any]     				=						hidden_states + (hidden_state,)

        lowerCamelCase__     :			str     				=						stage_module(lowerCamelCase_,     training=lowerCamelCase_					)

       if output_hidden_states:
        lowerCamelCase__     :			List[Any]     				=						hidden_states + (hidden_state,)

       if not return_dict:
        return tuple(v for v in [hidden_state, hidden_states] if v is not None					)

       return TFBaseModelOutputWithNoAttention(last_hidden_state=lowerCamelCase_,     hidden_states=lowerCamelCase_					)



class 		a_      (	snake_case_ ):







      '''simple docstring'''

      lowerCamelCase__       :				Dict =	ResNetConfig
      lowerCamelCase__       :				Union[str, Any] =	'resnet'
      lowerCamelCase__       :				int =	'pixel_values'




      @property
      def 			a__							(self					):

       '''simple docstring'''



       return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_2_4, 2_2_4),     dtype=tf.floataa					)}


A_			: Optional[Any]				=			r"\n    This model is a TensorFlow\n    [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a\n    regular TensorFlow Module and refer to the TensorFlow documentation for all matter related to general usage and\n    behavior.\n\n    Parameters:\n        config ([`ResNetConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.\n"


A_			: List[str]				=			r"\n    Args:\n        pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n            [`ConvNextImageProcessor.__call__`] for details.\n\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n            more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n"



@keras_serializable
class 		a_      (	tf.keras.layers.Layer ):







      '''simple docstring'''

      lowerCamelCase__       :				int =	ResNetConfig




      def __init__(self,     lowerCamelCase_,     **lowerCamelCase_					):

       '''simple docstring'''



       super().__init__(**lowerCamelCase_					)
       lowerCamelCase__     :			Optional[int]     				=						config
       lowerCamelCase__     :			Dict     				=						TFResNetEmbeddings(lowerCamelCase_,     name='embedder'					)
       lowerCamelCase__     :			Dict     				=						TFResNetEncoder(lowerCamelCase_,     name='encoder'					)
       lowerCamelCase__     :			Union[str, Any]     				=						tf.keras.layers.GlobalAveragePoolingaD(keepdims=lowerCamelCase_					)





      @unpack_inputs
      def 			a__							(self,     lowerCamelCase_,     lowerCamelCase_ = None,     lowerCamelCase_ = None,     lowerCamelCase_ = False,     ):

       '''simple docstring'''



       lowerCamelCase__     :			int     				=						(
           output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
       )
       lowerCamelCase__     :			Union[str, Any]     				=						return_dict if return_dict is not None else self.config.use_return_dict

       # TF 2.0 image layers can't use NCHW format when running on CPU.
       # We transpose to NHWC format and then transpose back after the full forward pass.
       # (batch_size, num_channels, height, width) -> (batch_size, height, width, num_channels)
       lowerCamelCase__     :			str     				=						tf.transpose(lowerCamelCase_,     perm=[0, 2, 3, 1]					)
       lowerCamelCase__     :			List[Any]     				=						self.embedder(lowerCamelCase_,     training=lowerCamelCase_					)

       lowerCamelCase__     :			str     				=						self.encoder(
           lowerCamelCase_,     output_hidden_states=lowerCamelCase_,     return_dict=lowerCamelCase_,     training=lowerCamelCase_					)

       lowerCamelCase__     :			Union[str, Any]     				=						encoder_outputs[0]

       lowerCamelCase__     :			Dict     				=						self.pooler(lowerCamelCase_					)

       # Transpose all the outputs to the NCHW format
       # (batch_size, height, width, num_channels) -> (batch_size, num_channels, height, width)
       lowerCamelCase__     :			List[Any]     				=						tf.transpose(lowerCamelCase_,     (0, 3, 1, 2)					)
       lowerCamelCase__     :			Optional[int]     				=						tf.transpose(lowerCamelCase_,     (0, 3, 1, 2)					)
       lowerCamelCase__     :			Optional[Any]     				=						()
       for hidden_state in encoder_outputs[1:]:
        lowerCamelCase__     :			Optional[int]     				=						hidden_states + tuple(tf.transpose(lowerCamelCase_,     (0, 3, 1, 2)					) for h in hidden_state					)

       if not return_dict:
        return (last_hidden_state, pooled_output) + hidden_states

       lowerCamelCase__     :			Optional[int]     				=						hidden_states if output_hidden_states else None

       return TFBaseModelOutputWithPoolingAndNoAttention(
           last_hidden_state=lowerCamelCase_,     pooler_output=lowerCamelCase_,     hidden_states=lowerCamelCase_,     )



@add_start_docstrings(
    'The bare ResNet model outputting raw features without any specific head on top.'  ,						snake_case_  ,						)
class 		a_      (	snake_case_ ):







      '''simple docstring'''

      def __init__(self,     lowerCamelCase_,     **lowerCamelCase_					):

       '''simple docstring'''



       super().__init__(lowerCamelCase_,     **lowerCamelCase_					)
       lowerCamelCase__     :			int     				=						TFResNetMainLayer(config=lowerCamelCase_,     name='resnet'					)





      @add_start_docstrings_to_model_forward(lowerCamelCase_					)
      @add_code_sample_docstrings(
          checkpoint=_CHECKPOINT_FOR_DOC,     output_type=lowerCamelCase_,     config_class=_CONFIG_FOR_DOC,     modality='vision',     expected_output=_EXPECTED_OUTPUT_SHAPE,     )
      @unpack_inputs
      def 			a__							(self,     lowerCamelCase_,     lowerCamelCase_ = None,     lowerCamelCase_ = None,     lowerCamelCase_ = False,     ):

       '''simple docstring'''



       lowerCamelCase__     :			Any     				=						(
           output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
       )
       lowerCamelCase__     :			Optional[Any]     				=						return_dict if return_dict is not None else self.config.use_return_dict

       lowerCamelCase__     :			List[Any]     				=						self.resnet(
           pixel_values=lowerCamelCase_,     output_hidden_states=lowerCamelCase_,     return_dict=lowerCamelCase_,     training=lowerCamelCase_,     )
       return resnet_outputs



@add_start_docstrings(
    '\n    ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    '  ,						snake_case_  ,						)
class 		a_      (	snake_case_  ,						snake_case_ ):







      '''simple docstring'''

      def __init__(self,     lowerCamelCase_,     **lowerCamelCase_					):

       '''simple docstring'''



       super().__init__(lowerCamelCase_,     **lowerCamelCase_					)
       lowerCamelCase__     :			int     				=						config.num_labels
       lowerCamelCase__     :			Dict     				=						TFResNetMainLayer(lowerCamelCase_,     name='resnet'					)
       # classification head
       lowerCamelCase__     :			Any     				=						(
           tf.keras.layers.Dense(config.num_labels,     name='classifier.1'					)
           if config.num_labels > 0
           else tf.keras.layers.Activation('linear',     name='classifier.1'					)
       )




      def 			a__							(self,     lowerCamelCase_					):

       '''simple docstring'''



       lowerCamelCase__     :			Optional[Any]     				=						tf.keras.layers.Flatten()(lowerCamelCase_					)
       lowerCamelCase__     :			Tuple     				=						self.classifier_layer(lowerCamelCase_					)
       return logits





      @add_start_docstrings_to_model_forward(lowerCamelCase_					)
      @add_code_sample_docstrings(
          checkpoint=_IMAGE_CLASS_CHECKPOINT,     output_type=lowerCamelCase_,     config_class=_CONFIG_FOR_DOC,     expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,     )
      @unpack_inputs
      def 			a__							(self,     lowerCamelCase_ = None,     lowerCamelCase_ = None,     lowerCamelCase_ = None,     lowerCamelCase_ = None,     lowerCamelCase_ = False,     ):

       '''simple docstring'''



       lowerCamelCase__     :			List[str]     				=						return_dict if return_dict is not None else self.config.use_return_dict

       lowerCamelCase__     :			Tuple     				=						self.resnet(
           lowerCamelCase_,     output_hidden_states=lowerCamelCase_,     return_dict=lowerCamelCase_,     training=lowerCamelCase_					)

       lowerCamelCase__     :			Dict     				=						outputs.pooler_output if return_dict else outputs[1]

       lowerCamelCase__     :			List[str]     				=						self.classifier(lowerCamelCase_					)

       lowerCamelCase__     :			List[str]     				=						None if labels is None else self.hf_compute_loss(lowerCamelCase_,     lowerCamelCase_					)

       if not return_dict:
        lowerCamelCase__     :			Union[str, Any]     				=						(logits,) + outputs[2:]
        return (loss,) + output if loss is not None else output

       return TFImageClassifierOutputWithNoAttention(loss=lowerCamelCase_,     logits=lowerCamelCase_,     hidden_states=outputs.hidden_states					)









"""simple docstring"""
import json
import os
import random
import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import BertTokenizer, BertTokenizerFast
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available


if is_vision_available():
      from PIL import Image

      from transformers import FlavaImageProcessor, FlavaProcessor
      from transformers.models.flava.image_processing_flava import (
          FLAVA_CODEBOOK_MEAN,
          FLAVA_CODEBOOK_STD,
          FLAVA_IMAGE_MEAN,
          FLAVA_IMAGE_STD,
      )



@require_vision
class 		a_      (	unittest.TestCase ):







      '''simple docstring'''

      def 			a__							(self					):

       '''simple docstring'''



       lowerCamelCase__     :			Union[str, Any]     				=						tempfile.mkdtemp()

       # fmt: off
       lowerCamelCase__     :			List[str]     				=						['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest']
       # fmt: on
       lowerCamelCase__     :			List[Any]     				=						os.path.join(self.tmpdirname,     VOCAB_FILES_NAMES['vocab_file']					)

       with open(self.vocab_file,     'w',     encoding='utf-8'					) as fp:
        fp.write(''.join([x + '\n' for x in vocab_tokens]					)					)

       lowerCamelCase__     :			List[Any]     				=						{
           'image_mean': FLAVA_IMAGE_MEAN,
           'image_std': FLAVA_IMAGE_STD,
           'do_normalize': True,
           'do_resize': True,
           'size': 2_2_4,
           'do_center_crop': True,
           'crop_size': 2_2_4,
           'input_size_patches': 1_4,
           'total_mask_patches': 7_5,
           'mask_group_max_patches': None,
           'mask_group_min_patches': 1_6,
           'mask_group_min_aspect_ratio': 0.3,
           'mask_group_max_aspect_ratio': None,
           'codebook_do_resize': True,
           'codebook_size': 1_1_2,
           'codebook_do_center_crop': True,
           'codebook_crop_size': 1_1_2,
           'codebook_do_map_pixels': True,
           'codebook_do_normalize': True,
           'codebook_image_mean': FLAVA_CODEBOOK_MEAN,
           'codebook_image_std': FLAVA_CODEBOOK_STD,
       }

       lowerCamelCase__     :			List[str]     				=						os.path.join(self.tmpdirname,     lowerCamelCase_					)
       with open(self.image_processor_file,     'w',     encoding='utf-8'					) as fp:
        json.dump(lowerCamelCase_,     lowerCamelCase_					)




      def 			a__							(self,     **lowerCamelCase_					):

       '''simple docstring'''



       return BertTokenizer.from_pretrained(self.tmpdirname,     **lowerCamelCase_					)




      def 			a__							(self,     **lowerCamelCase_					):

       '''simple docstring'''



       return BertTokenizerFast.from_pretrained(self.tmpdirname,     **lowerCamelCase_					)




      def 			a__							(self,     **lowerCamelCase_					):

       '''simple docstring'''



       return FlavaImageProcessor.from_pretrained(self.tmpdirname,     **lowerCamelCase_					)




      def 			a__							(self					):

       '''simple docstring'''



       shutil.rmtree(self.tmpdirname					)




      def 			a__							(self					):

       '''simple docstring'''



       lowerCamelCase__     :			Optional[Any]     				=						[np.random.randint(2_5_5,     size=(3, 3_0, 4_0_0),     dtype=np.uinta					)]

       lowerCamelCase__     :			Union[str, Any]     				=						[Image.fromarray(np.moveaxis(lowerCamelCase_,     0,     -1					)					) for x in image_inputs]

       return image_inputs




      def 			a__							(self					):

       '''simple docstring'''



       lowerCamelCase__     :			Union[str, Any]     				=						self.get_tokenizer()
       lowerCamelCase__     :			Dict     				=						self.get_rust_tokenizer()
       lowerCamelCase__     :			Union[str, Any]     				=						self.get_image_processor()

       lowerCamelCase__     :			Tuple     				=						FlavaProcessor(tokenizer=lowerCamelCase_,     image_processor=lowerCamelCase_					)
       processor_slow.save_pretrained(self.tmpdirname					)
       lowerCamelCase__     :			str     				=						FlavaProcessor.from_pretrained(self.tmpdirname,     use_fast=lowerCamelCase_					)

       lowerCamelCase__     :			List[str]     				=						FlavaProcessor(tokenizer=lowerCamelCase_,     image_processor=lowerCamelCase_					)
       processor_fast.save_pretrained(self.tmpdirname					)
       lowerCamelCase__     :			List[str]     				=						FlavaProcessor.from_pretrained(self.tmpdirname					)

       self.assertEqual(processor_slow.tokenizer.get_vocab(),     tokenizer_slow.get_vocab()					)
       self.assertEqual(processor_fast.tokenizer.get_vocab(),     tokenizer_fast.get_vocab()					)
       self.assertEqual(tokenizer_slow.get_vocab(),     tokenizer_fast.get_vocab()					)
       self.assertIsInstance(processor_slow.tokenizer,     lowerCamelCase_					)
       self.assertIsInstance(processor_fast.tokenizer,     lowerCamelCase_					)

       self.assertEqual(processor_slow.image_processor.to_json_string(),     image_processor.to_json_string()					)
       self.assertEqual(processor_fast.image_processor.to_json_string(),     image_processor.to_json_string()					)
       self.assertIsInstance(processor_slow.image_processor,     lowerCamelCase_					)
       self.assertIsInstance(processor_fast.image_processor,     lowerCamelCase_					)




      def 			a__							(self					):

       '''simple docstring'''



       lowerCamelCase__     :			Optional[Any]     				=						FlavaProcessor(tokenizer=self.get_tokenizer(),     image_processor=self.get_image_processor()					)
       processor.save_pretrained(self.tmpdirname					)

       lowerCamelCase__     :			List[str]     				=						self.get_tokenizer(bos_token='(BOS)',     eos_token='(EOS)'					)
       lowerCamelCase__     :			List[str]     				=						self.get_image_processor(do_normalize=lowerCamelCase_,     padding_value=1.0					)

       lowerCamelCase__     :			Dict     				=						FlavaProcessor.from_pretrained(
           self.tmpdirname,     bos_token='(BOS)',     eos_token='(EOS)',     do_normalize=lowerCamelCase_,     padding_value=1.0					)

       self.assertEqual(processor.tokenizer.get_vocab(),     tokenizer_add_kwargs.get_vocab()					)
       self.assertIsInstance(processor.tokenizer,     lowerCamelCase_					)

       self.assertEqual(processor.image_processor.to_json_string(),     image_processor_add_kwargs.to_json_string()					)
       self.assertIsInstance(processor.image_processor,     lowerCamelCase_					)




      def 			a__							(self					):

       '''simple docstring'''



       lowerCamelCase__     :			Tuple     				=						self.get_image_processor()
       lowerCamelCase__     :			Union[str, Any]     				=						self.get_tokenizer()

       lowerCamelCase__     :			Optional[Any]     				=						FlavaProcessor(tokenizer=lowerCamelCase_,     image_processor=lowerCamelCase_					)

       lowerCamelCase__     :			Tuple     				=						self.prepare_image_inputs()

       lowerCamelCase__     :			List[str]     				=						image_processor(lowerCamelCase_,     return_tensors='np'					)
       lowerCamelCase__     :			Optional[Any]     				=						processor(images=lowerCamelCase_,     return_tensors='np'					)

       for key in input_feat_extract.keys():
        self.assertAlmostEqual(input_feat_extract[key].sum(),     input_processor[key].sum(),     delta=1e-2					)

       # With rest of the args
       random.seed(1_2_3_4					)
       lowerCamelCase__     :			Optional[Any]     				=						image_processor(
           lowerCamelCase_,     return_image_mask=lowerCamelCase_,     return_codebook_pixels=lowerCamelCase_,     return_tensors='np'					)
       random.seed(1_2_3_4					)
       lowerCamelCase__     :			Optional[Any]     				=						processor(
           images=lowerCamelCase_,     return_image_mask=lowerCamelCase_,     return_codebook_pixels=lowerCamelCase_,     return_tensors='np'					)

       for key in input_feat_extract.keys():
        self.assertAlmostEqual(input_feat_extract[key].sum(),     input_processor[key].sum(),     delta=1e-2					)




      def 			a__							(self					):

       '''simple docstring'''



       lowerCamelCase__     :			Dict     				=						self.get_image_processor()
       lowerCamelCase__     :			Union[str, Any]     				=						self.get_tokenizer()

       lowerCamelCase__     :			Tuple     				=						FlavaProcessor(tokenizer=lowerCamelCase_,     image_processor=lowerCamelCase_					)

       lowerCamelCase__     :			Optional[int]     				=						'lower newer'

       lowerCamelCase__     :			Union[str, Any]     				=						processor(text=lowerCamelCase_					)

       lowerCamelCase__     :			Union[str, Any]     				=						tokenizer(lowerCamelCase_					)

       for key in encoded_tok.keys():
        self.assertListEqual(encoded_tok[key],     encoded_processor[key]					)




      def 			a__							(self					):

       '''simple docstring'''



       lowerCamelCase__     :			Any     				=						self.get_image_processor()
       lowerCamelCase__     :			Optional[int]     				=						self.get_tokenizer()

       lowerCamelCase__     :			List[str]     				=						FlavaProcessor(tokenizer=lowerCamelCase_,     image_processor=lowerCamelCase_					)

       lowerCamelCase__     :			str     				=						'lower newer'
       lowerCamelCase__     :			Union[str, Any]     				=						self.prepare_image_inputs()

       lowerCamelCase__     :			Optional[int]     				=						processor(text=lowerCamelCase_,     images=lowerCamelCase_					)

       self.assertListEqual(list(inputs.keys()					),     ['input_ids', 'token_type_ids', 'attention_mask', 'pixel_values']					)

       # add extra args
       lowerCamelCase__     :			Tuple     				=						processor(text=lowerCamelCase_,     images=lowerCamelCase_,     return_codebook_pixels=lowerCamelCase_,     return_image_mask=lowerCamelCase_					)

       self.assertListEqual(
           list(inputs.keys()					),     [
               'input_ids',
               'token_type_ids',
               'attention_mask',
               'pixel_values',
               'codebook_pixel_values',
               'bool_masked_pos',
           ],     )

       # test if it raises when no input is passed
       with pytest.raises(lowerCamelCase_					):
        processor()




      def 			a__							(self					):

       '''simple docstring'''



       lowerCamelCase__     :			int     				=						self.get_image_processor()
       lowerCamelCase__     :			List[str]     				=						self.get_tokenizer()

       lowerCamelCase__     :			Tuple     				=						FlavaProcessor(tokenizer=lowerCamelCase_,     image_processor=lowerCamelCase_					)

       lowerCamelCase__     :			str     				=						[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

       lowerCamelCase__     :			str     				=						processor.batch_decode(lowerCamelCase_					)
       lowerCamelCase__     :			List[Any]     				=						tokenizer.batch_decode(lowerCamelCase_					)

       self.assertListEqual(lowerCamelCase_,     lowerCamelCase_					)





      def 			a__							(self					):

       '''simple docstring'''



       lowerCamelCase__     :			Optional[Any]     				=						self.get_image_processor()
       lowerCamelCase__     :			Union[str, Any]     				=						self.get_tokenizer()

       lowerCamelCase__     :			Union[str, Any]     				=						FlavaProcessor(tokenizer=lowerCamelCase_,     image_processor=lowerCamelCase_					)

       lowerCamelCase__     :			List[Any]     				=						'lower newer'
       lowerCamelCase__     :			Optional[int]     				=						self.prepare_image_inputs()

       lowerCamelCase__     :			List[str]     				=						processor(text=lowerCamelCase_,     images=lowerCamelCase_					)

       self.assertListEqual(list(inputs.keys()					),     processor.model_input_names					)

