

import json
import os
import shutil
import tempfile
import unittest

import numpy as np

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


if is_vision_available():
			from PIL import Image

			from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor






@require_tokenizers
@require_vision
class _UpperCamelCase							(							unittest.TestCase   ):
			'''simple docstring'''







			def 							__UpperCamelCase (			self							: Tuple	)							->       List[str]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      Any				     =       tempfile.mkdtemp()

				# fmt: off
				SCREAMING_SNAKE_CASE   :      str				     =       ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest"]
				# fmt: on
				SCREAMING_SNAKE_CASE   :      int				     =       os.path.join(self.tmpdirname      ,      VOCAB_FILES_NAMES["vocab_file"]	)
				with open(self.vocab_file      ,      "w"      ,      encoding="utf-8"	) as vocab_writer:
					vocab_writer.write("".join([x + "\n" for x in vocab_tokens]	)	)

				SCREAMING_SNAKE_CASE   :      Dict				     =       {
				    "do_resize": True,
				    "size": {"height": 18, "width": 18},
				    "do_normalize": True,
				    "image_mean": [0.5, 0.5, 0.5],
				    "image_std": [0.5, 0.5, 0.5],
				}
				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       os.path.join(self.tmpdirname      ,      a	)
				with open(self.image_processor_file      ,      "w"      ,      encoding="utf-8"	) as fp:
					json.dump(a      ,      a	)
			def 							__UpperCamelCase (			self							: Union[str, Any]      ,      **a							: Optional[Any]	)							->       Union[str, Any]:

				"""simple docstring"""

				return BertTokenizer.from_pretrained(self.tmpdirname      ,      **a	)
			def 							__UpperCamelCase (			self							: Tuple      ,      **a							: List[str]	)							->       Tuple:

				"""simple docstring"""

				return ViTImageProcessor.from_pretrained(self.tmpdirname      ,      **a	)
			def 							__UpperCamelCase (			self							: Optional[Any]	)							->       Tuple:

				"""simple docstring"""

				shutil.rmtree(self.tmpdirname	)
			def 							__UpperCamelCase (			self							: Optional[int]	)							->       Any:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      Optional[int]				     =       [np.random.randint(255      ,      size=(3, 30, 400)      ,      dtype=np.uinta	)]

				SCREAMING_SNAKE_CASE   :      Tuple				     =       [Image.fromarray(np.moveaxis(a      ,      0      ,      -1	)	) for x in image_inputs]

				return image_inputs
			def 							__UpperCamelCase (			self							: Optional[Any]	)							->       Tuple:

				"""simple docstring"""

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

				SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       VisionTextDualEncoderProcessor(tokenizer=a      ,      image_processor=a	)

				processor.save_pretrained(self.tmpdirname	)
				SCREAMING_SNAKE_CASE   :      str				     =       VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname	)

				self.assertEqual(processor.tokenizer.get_vocab()      ,      tokenizer.get_vocab()	)
				self.assertIsInstance(processor.tokenizer      ,      (BertTokenizer, BertTokenizerFast)	)

				self.assertEqual(processor.image_processor.to_json_string()      ,      image_processor.to_json_string()	)
				self.assertIsInstance(processor.image_processor      ,      a	)
			def 							__UpperCamelCase (			self							: str	)							->       Union[str, Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      str				     =       VisionTextDualEncoderProcessor(
				    tokenizer=self.get_tokenizer()      ,      image_processor=self.get_image_processor()	)
				processor.save_pretrained(self.tmpdirname	)

				SCREAMING_SNAKE_CASE   :      Optional[int]				     =       self.get_tokenizer(bos_token="(BOS)"      ,      eos_token="(EOS)"	)
				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       self.get_image_processor(do_normalize=a      ,      padding_value=1.0	)

				SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       VisionTextDualEncoderProcessor.from_pretrained(
				    self.tmpdirname      ,      bos_token="(BOS)"      ,      eos_token="(EOS)"      ,      do_normalize=a      ,      padding_value=1.0	)

				self.assertEqual(processor.tokenizer.get_vocab()      ,      tokenizer_add_kwargs.get_vocab()	)
				self.assertIsInstance(processor.tokenizer      ,      (BertTokenizer, BertTokenizerFast)	)

				self.assertEqual(processor.image_processor.to_json_string()      ,      image_processor_add_kwargs.to_json_string()	)
				self.assertIsInstance(processor.image_processor      ,      a	)
			def 							__UpperCamelCase (			self							: Tuple	)							->       List[str]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       self.get_image_processor()
				SCREAMING_SNAKE_CASE   :      str				     =       self.get_tokenizer()

				SCREAMING_SNAKE_CASE   :      List[str]				     =       VisionTextDualEncoderProcessor(tokenizer=a      ,      image_processor=a	)

				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       self.prepare_image_inputs()

				SCREAMING_SNAKE_CASE   :      int				     =       image_processor(a      ,      return_tensors="np"	)
				SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       processor(images=a      ,      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 							__UpperCamelCase (			self							: List[str]	)							->       Dict:

				"""simple docstring"""

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

				SCREAMING_SNAKE_CASE   :      Dict				     =       VisionTextDualEncoderProcessor(tokenizer=a      ,      image_processor=a	)

				SCREAMING_SNAKE_CASE   :      Tuple				     =       "lower newer"

				SCREAMING_SNAKE_CASE   :      List[str]				     =       processor(text=a	)

				SCREAMING_SNAKE_CASE   :      List[Any]				     =       tokenizer(a	)

				for key in encoded_tok.keys():
					self.assertListEqual(encoded_tok[key]      ,      encoded_processor[key]	)
			def 							__UpperCamelCase (			self							: Tuple	)							->       Optional[Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      Dict				     =       self.get_image_processor()
				SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       self.get_tokenizer()

				SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       VisionTextDualEncoderProcessor(tokenizer=a      ,      image_processor=a	)

				SCREAMING_SNAKE_CASE   :      Dict				     =       "lower newer"
				SCREAMING_SNAKE_CASE   :      int				     =       self.prepare_image_inputs()

				SCREAMING_SNAKE_CASE   :      Optional[int]				     =       processor(text=a      ,      images=a	)

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

				# test if it raises when no input is passed
				with self.assertRaises(a	):
					processor()
			def 							__UpperCamelCase (			self							: Optional[int]	)							->       Optional[Any]:

				"""simple docstring"""

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

				SCREAMING_SNAKE_CASE   :      int				     =       VisionTextDualEncoderProcessor(tokenizer=a      ,      image_processor=a	)

				SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       processor.batch_decode(a	)
				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       tokenizer.batch_decode(a	)

				self.assertListEqual(a      ,      a	)






			def 							__UpperCamelCase (			self							: str	)							->       Optional[int]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      List[str]				     =       self.get_image_processor()
				SCREAMING_SNAKE_CASE   :      Dict				     =       self.get_tokenizer()

				SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       VisionTextDualEncoderProcessor(tokenizer=a      ,      image_processor=a	)

				SCREAMING_SNAKE_CASE   :      List[Any]				     =       "lower newer"
				SCREAMING_SNAKE_CASE   :      int				     =       self.prepare_image_inputs()

				SCREAMING_SNAKE_CASE   :      List[Any]				     =       processor(text=a      ,      images=a	)

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


from dataclasses import dataclass
from typing import Optional

import torch
from torch import nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .attention import BasicTransformerBlock
from .modeling_utils import ModelMixin






@dataclass
class _UpperCamelCase							(							__A   ):
			'''simple docstring'''







			lowerCamelCase__           =42






class _UpperCamelCase							(							__A							,	__A   ):
			'''simple docstring'''







			@register_to_config
			def __init__(			self							: str      ,      a							: int = 16      ,      a							: int = 88      ,      a							: Optional[int] = None      ,      a							: Optional[int] = None      ,      a							: int = 1      ,      a							: float = 0.0      ,      a							: int = 32      ,      a							: Optional[int] = None      ,      a							: bool = False      ,      a							: Optional[int] = None      ,      a							: str = "geglu"      ,      a							: bool = True      ,      a							: bool = True      ,      )							->       str:

				"""simple docstring"""

				super().__init__()
				SCREAMING_SNAKE_CASE   :      str				     =       num_attention_heads
				SCREAMING_SNAKE_CASE   :      Tuple				     =       attention_head_dim
				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       num_attention_heads * attention_head_dim

				SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       in_channels

				SCREAMING_SNAKE_CASE   :      List[Any]				     =       torch.nn.GroupNorm(num_groups=a      ,      num_channels=a      ,      eps=1e-6      ,      affine=a	)
				SCREAMING_SNAKE_CASE   :      List[Any]				     =       nn.Linear(a      ,      a	)

				# 3. Define transformers blocks
				SCREAMING_SNAKE_CASE   :      List[str]				     =       nn.ModuleList(
				    [
				        BasicTransformerBlock(
				            a      ,      a      ,      a      ,      dropout=a      ,      cross_attention_dim=a      ,      activation_fn=a      ,      attention_bias=a      ,      double_self_attention=a      ,      norm_elementwise_affine=a      ,      )
				        for d in range(a	)
				    ]	)

				SCREAMING_SNAKE_CASE   :      Optional[int]				     =       nn.Linear(a      ,      a	)






			def 							__UpperCamelCase (			self							: Any      ,      a							: int      ,      a							: Optional[int]=None      ,      a							: List[str]=None      ,      a							: List[str]=None      ,      a							: Union[str, Any]=1      ,      a							: Any=None      ,      a							: bool = True      ,      )							->       Tuple:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE     ,SCREAMING_SNAKE_CASE     ,SCREAMING_SNAKE_CASE     ,SCREAMING_SNAKE_CASE   :      Any				     =       hidden_states.shape
				SCREAMING_SNAKE_CASE   :      Any				     =       batch_frames // num_frames

				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       hidden_states

				SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       hidden_states[None, :].reshape(a      ,      a      ,      a      ,      a      ,      a	)
				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       hidden_states.permute(0      ,      2      ,      1      ,      3      ,      4	)

				SCREAMING_SNAKE_CASE   :      Tuple				     =       self.norm(a	)
				SCREAMING_SNAKE_CASE   :      List[Any]				     =       hidden_states.permute(0      ,      3      ,      4      ,      2      ,      1	).reshape(batch_size * height * width      ,      a      ,      a	)

				SCREAMING_SNAKE_CASE   :      List[Any]				     =       self.proj_in(a	)

				# 2. Blocks
				for block in self.transformer_blocks:
					SCREAMING_SNAKE_CASE   :      Optional[int]				     =       block(
					    a      ,      encoder_hidden_states=a      ,      timestep=a      ,      cross_attention_kwargs=a      ,      class_labels=a      ,      )

				# 3. Output
				SCREAMING_SNAKE_CASE   :      List[str]				     =       self.proj_out(a	)
				SCREAMING_SNAKE_CASE   :      int				     =       (
				    hidden_states[None, None, :]
				    .reshape(a      ,      a      ,      a      ,      a      ,      a	)
				    .permute(0      ,      3      ,      4      ,      1      ,      2	)
				    .contiguous()
				)
				SCREAMING_SNAKE_CASE   :      Dict				     =       hidden_states.reshape(a      ,      a      ,      a      ,      a	)

				SCREAMING_SNAKE_CASE   :      int				     =       hidden_states + residual

				if not return_dict:
					return (output,)

				return TransformerTemporalModelOutput(sample=a	)