'''simple docstring'''





import os
import pickle
import tempfile
import unittest
from typing import Callable, Optional

import numpy as np

from transformers import (
    BatchEncoding,
    BertTokenizer,
    BertTokenizerFast,
    PreTrainedTokenizer,
    PreTrainedTokenizerFast,
    TensorType,
    TokenSpan,
    is_tokenizers_available,
)
from transformers.models.gpta.tokenization_gpta import GPTaTokenizer
from transformers.testing_utils import CaptureStderr, require_flax, require_tf, require_tokenizers, require_torch, slow


if is_tokenizers_available():
      from tokenizers import Tokenizer
      from tokenizers.models import WordPiece



class   UpperCamelCase					(       unittest.TestCase       ):







    """simple docstring"""





    def    SCREAMING_SNAKE_CASE_     (					self     :						Dict							,							UpperCAmelCase_     :						List[str]):


         """simple docstring"""







         a					:							List[str]							= list(tokenizer_class.max_model_input_sizes.keys())
         for model_name in sa_models[:1]:
              a					:							Tuple							= tokenizer_class.from_pretrained(UpperCAmelCase_)
              self.assertIsNotNone(UpperCAmelCase_)
              self.assertIsInstance(UpperCAmelCase_							,							UpperCAmelCase_)
              self.assertIsInstance(UpperCAmelCase_							,							UpperCAmelCase_)

              for special_tok in tokenizer.all_special_tokens:
                   self.assertIsInstance(UpperCAmelCase_							,							UpperCAmelCase_)
                   a					:							Tuple							= tokenizer.convert_tokens_to_ids(UpperCAmelCase_)
                   self.assertIsInstance(UpperCAmelCase_							,							UpperCAmelCase_)





    def    SCREAMING_SNAKE_CASE_     (					self     :						Dict							,							UpperCAmelCase_     :						BatchEncoding							,							UpperCAmelCase_     :						Optional[Callable] = None):


         """simple docstring"""







         a					:							str							= pickle.dumps(UpperCAmelCase_)
         self.assertIsNotNone(UpperCAmelCase_)

         a					:							Tuple							= pickle.loads(UpperCAmelCase_)

         # Ensure is_fast is correctly restored
         self.assertEqual(be_restored.is_fast							,							be_original.is_fast)

         # Ensure encodings are potentially correctly restored
         if be_original.is_fast:
              self.assertIsNotNone(be_restored.encodings)
         else:
              self.assertIsNone(be_restored.encodings)

         # Ensure the keys are the same
         for original_v, restored_v in zip(be_original.values()							,							be_restored.values()):
              if equal_op:
                   self.assertTrue(equal_op(UpperCAmelCase_							,							UpperCAmelCase_))
              else:
                   self.assertEqual(UpperCAmelCase_							,							UpperCAmelCase_)





    @slow
    def    SCREAMING_SNAKE_CASE_     (					self     :						Optional[Any]):


         """simple docstring"""







         self.check_tokenizer_from_pretrained(UpperCAmelCase_)





    def    SCREAMING_SNAKE_CASE_     (					self     :						Tuple):


         """simple docstring"""







         self.assertEqual(TensorType('tf')							,							TensorType.TENSORFLOW)
         self.assertEqual(TensorType('pt')							,							TensorType.PYTORCH)
         self.assertEqual(TensorType('np')							,							TensorType.NUMPY)





    @require_tokenizers
    def    SCREAMING_SNAKE_CASE_     (					self     :						Union[str, Any]):


         """simple docstring"""







         import numpy as np

         a					:							Union[str, Any]							= BertTokenizer.from_pretrained('bert-base-cased')
         a					:							Optional[int]							= BertTokenizerFast.from_pretrained('bert-base-cased')

         # Python no tensor
         with self.subTest('BatchEncoding (Python, return_tensors=None)'):
              self.assert_dump_and_restore(tokenizer_p('Small example to encode'))

         with self.subTest('BatchEncoding (Python, return_tensors=NUMPY)'):
              self.assert_dump_and_restore(
                  tokenizer_p('Small example to encode'							,							return_tensors=TensorType.NUMPY)							,							np.array_equal)

         with self.subTest('BatchEncoding (Rust, return_tensors=None)'):
              self.assert_dump_and_restore(tokenizer_r('Small example to encode'))

         with self.subTest('BatchEncoding (Rust, return_tensors=NUMPY)'):
              self.assert_dump_and_restore(
                  tokenizer_r('Small example to encode'							,							return_tensors=TensorType.NUMPY)							,							np.array_equal)





    @require_tf
    @require_tokenizers
    def    SCREAMING_SNAKE_CASE_     (					self     :						Tuple):


         """simple docstring"""







         import tensorflow as tf

         def tf_array_equals(UpperCAmelCase_     :						List[Any]							,							UpperCAmelCase_     :						Optional[Any]):
              return tf.reduce_all(tf.equal(UpperCAmelCase_							,							UpperCAmelCase_))

         a					:							List[Any]							= BertTokenizer.from_pretrained('bert-base-cased')
         a					:							List[Any]							= BertTokenizerFast.from_pretrained('bert-base-cased')

         with self.subTest('BatchEncoding (Python, return_tensors=TENSORFLOW)'):
              self.assert_dump_and_restore(
                  tokenizer_p('Small example to encode'							,							return_tensors=TensorType.TENSORFLOW)							,							UpperCAmelCase_)

         with self.subTest('BatchEncoding (Rust, return_tensors=TENSORFLOW)'):
              self.assert_dump_and_restore(
                  tokenizer_r('Small example to encode'							,							return_tensors=TensorType.TENSORFLOW)							,							UpperCAmelCase_)





    @require_torch
    @require_tokenizers
    def    SCREAMING_SNAKE_CASE_     (					self     :						Tuple):


         """simple docstring"""







         import torch

         a					:							Union[str, Any]							= BertTokenizer.from_pretrained('bert-base-cased')
         a					:							int							= BertTokenizerFast.from_pretrained('bert-base-cased')

         with self.subTest('BatchEncoding (Python, return_tensors=PYTORCH)'):
              self.assert_dump_and_restore(
                  tokenizer_p('Small example to encode'							,							return_tensors=TensorType.PYTORCH)							,							torch.equal)

         with self.subTest('BatchEncoding (Rust, return_tensors=PYTORCH)'):
              self.assert_dump_and_restore(
                  tokenizer_r('Small example to encode'							,							return_tensors=TensorType.PYTORCH)							,							torch.equal)





    @require_tokenizers
    def    SCREAMING_SNAKE_CASE_     (					self     :						List[Any]):


         """simple docstring"""







         a					:							Union[str, Any]							= BertTokenizer.from_pretrained('bert-base-cased')
         a					:							Tuple							= BertTokenizerFast.from_pretrained('bert-base-cased')

         with self.subTest('Python Tokenizer'):
              self.assertFalse(tokenizer_p('Small example to_encode').is_fast)

         with self.subTest('Rust Tokenizer'):
              self.assertTrue(tokenizer_r('Small example to_encode').is_fast)





    @require_tokenizers
    def    SCREAMING_SNAKE_CASE_     (					self     :						Any):


         """simple docstring"""







         a					:							str							= BertTokenizerFast.from_pretrained('bert-base-cased')
         a					:							int							= tokenizer_r(['Test', '\xad', 'test']							,							is_split_into_words=UpperCAmelCase_)

         self.assertEqual(encoded.word_to_tokens(0)							,							TokenSpan(start=1							,							end=2))
         self.assertEqual(encoded.word_to_tokens(1)							,							UpperCAmelCase_)
         self.assertEqual(encoded.word_to_tokens(2)							,							TokenSpan(start=2							,							end=3))





    def    SCREAMING_SNAKE_CASE_     (					self     :						Any):


         """simple docstring"""







         a					:							Optional[Any]							= BatchEncoding({'inputs': [[1, 2, 3], [4, 5, 6]], 'labels': [0, 1]})
         a					:							Dict							= batch.convert_to_tensors(tensor_type='np')
         self.assertEqual(tensor_batch['inputs'].shape							,							(2, 3))
         self.assertEqual(tensor_batch['labels'].shape							,							(2,))
         # test converting the converted
         with CaptureStderr() as cs:
              a					:							Union[str, Any]							= batch.convert_to_tensors(tensor_type='np')
         self.assertFalse(len(cs.err)							,							msg=f"""should have no warning, but got {cs.err}""")

         a					:							Tuple							= BatchEncoding({'inputs': [1, 2, 3], 'labels': 0})
         a					:							Optional[int]							= batch.convert_to_tensors(tensor_type='np'							,							prepend_batch_axis=UpperCAmelCase_)
         self.assertEqual(tensor_batch['inputs'].shape							,							(1, 3))
         self.assertEqual(tensor_batch['labels'].shape							,							(1,))





    @require_torch
    def    SCREAMING_SNAKE_CASE_     (					self     :						Optional[int]):


         """simple docstring"""







         a					:							Dict							= BatchEncoding({'inputs': [[1, 2, 3], [4, 5, 6]], 'labels': [0, 1]})
         a					:							Optional[Any]							= batch.convert_to_tensors(tensor_type='pt')
         self.assertEqual(tensor_batch['inputs'].shape							,							(2, 3))
         self.assertEqual(tensor_batch['labels'].shape							,							(2,))
         # test converting the converted
         with CaptureStderr() as cs:
              a					:							List[str]							= batch.convert_to_tensors(tensor_type='pt')
         self.assertFalse(len(cs.err)							,							msg=f"""should have no warning, but got {cs.err}""")

         a					:							List[Any]							= BatchEncoding({'inputs': [1, 2, 3], 'labels': 0})
         a					:							int							= batch.convert_to_tensors(tensor_type='pt'							,							prepend_batch_axis=UpperCAmelCase_)
         self.assertEqual(tensor_batch['inputs'].shape							,							(1, 3))
         self.assertEqual(tensor_batch['labels'].shape							,							(1,))





    @require_tf
    def    SCREAMING_SNAKE_CASE_     (					self     :						List[str]):


         """simple docstring"""







         a					:							Tuple							= BatchEncoding({'inputs': [[1, 2, 3], [4, 5, 6]], 'labels': [0, 1]})
         a					:							Tuple							= batch.convert_to_tensors(tensor_type='tf')
         self.assertEqual(tensor_batch['inputs'].shape							,							(2, 3))
         self.assertEqual(tensor_batch['labels'].shape							,							(2,))
         # test converting the converted
         with CaptureStderr() as cs:
              a					:							Optional[int]							= batch.convert_to_tensors(tensor_type='tf')
         self.assertFalse(len(cs.err)							,							msg=f"""should have no warning, but got {cs.err}""")

         a					:							int							= BatchEncoding({'inputs': [1, 2, 3], 'labels': 0})
         a					:							Union[str, Any]							= batch.convert_to_tensors(tensor_type='tf'							,							prepend_batch_axis=UpperCAmelCase_)
         self.assertEqual(tensor_batch['inputs'].shape							,							(1, 3))
         self.assertEqual(tensor_batch['labels'].shape							,							(1,))





    @require_flax
    def    SCREAMING_SNAKE_CASE_     (					self     :						Optional[Any]):


         """simple docstring"""







         a					:							Any							= BatchEncoding({'inputs': [[1, 2, 3], [4, 5, 6]], 'labels': [0, 1]})
         a					:							Union[str, Any]							= batch.convert_to_tensors(tensor_type='jax')
         self.assertEqual(tensor_batch['inputs'].shape							,							(2, 3))
         self.assertEqual(tensor_batch['labels'].shape							,							(2,))
         # test converting the converted
         with CaptureStderr() as cs:
              a					:							Any							= batch.convert_to_tensors(tensor_type='jax')
         self.assertFalse(len(cs.err)							,							msg=f"""should have no warning, but got {cs.err}""")

         a					:							Dict							= BatchEncoding({'inputs': [1, 2, 3], 'labels': 0})
         a					:							Any							= batch.convert_to_tensors(tensor_type='jax'							,							prepend_batch_axis=UpperCAmelCase_)
         self.assertEqual(tensor_batch['inputs'].shape							,							(1, 3))
         self.assertEqual(tensor_batch['labels'].shape							,							(1,))





    def    SCREAMING_SNAKE_CASE_     (					self     :						List[Any]):


         """simple docstring"""







         a					:							Optional[int]							= [{'input_ids': np.array([0, 1, 2])}, {'input_ids': np.array([0, 1, 2, 3])}]
         a					:							Optional[Any]							= BertTokenizer.from_pretrained('bert-base-cased')

         a					:							List[str]							= tokenizer.pad(UpperCAmelCase_							,							padding=UpperCAmelCase_)
         self.assertTrue(isinstance(batch['input_ids']							,							np.ndarray))
         self.assertEqual(batch['input_ids'].tolist()							,							[[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]])
         a					:							List[Any]							= tokenizer.pad(UpperCAmelCase_							,							padding=UpperCAmelCase_							,							return_tensors='np')
         self.assertTrue(isinstance(batch['input_ids']							,							np.ndarray))
         self.assertEqual(batch['input_ids'].tolist()							,							[[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]])





    @require_torch
    def    SCREAMING_SNAKE_CASE_     (					self     :						Any):


         """simple docstring"""







         import torch

         a					:							List[Any]							= [{'input_ids': torch.tensor([0, 1, 2])}, {'input_ids': torch.tensor([0, 1, 2, 3])}]
         a					:							str							= BertTokenizer.from_pretrained('bert-base-cased')

         a					:							Dict							= tokenizer.pad(UpperCAmelCase_							,							padding=UpperCAmelCase_)
         self.assertTrue(isinstance(batch['input_ids']							,							torch.Tensor))
         self.assertEqual(batch['input_ids'].tolist()							,							[[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]])
         a					:							Dict							= tokenizer.pad(UpperCAmelCase_							,							padding=UpperCAmelCase_							,							return_tensors='pt')
         self.assertTrue(isinstance(batch['input_ids']							,							torch.Tensor))
         self.assertEqual(batch['input_ids'].tolist()							,							[[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]])





    @require_tf
    def    SCREAMING_SNAKE_CASE_     (					self     :						Dict):


         """simple docstring"""







         import tensorflow as tf

         a					:							Optional[Any]							= [{'input_ids': tf.constant([0, 1, 2])}, {'input_ids': tf.constant([0, 1, 2, 3])}]
         a					:							int							= BertTokenizer.from_pretrained('bert-base-cased')

         a					:							str							= tokenizer.pad(UpperCAmelCase_							,							padding=UpperCAmelCase_)
         self.assertTrue(isinstance(batch['input_ids']							,							tf.Tensor))
         self.assertEqual(batch['input_ids'].numpy().tolist()							,							[[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]])
         a					:							Union[str, Any]							= tokenizer.pad(UpperCAmelCase_							,							padding=UpperCAmelCase_							,							return_tensors='tf')
         self.assertTrue(isinstance(batch['input_ids']							,							tf.Tensor))
         self.assertEqual(batch['input_ids'].numpy().tolist()							,							[[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]])





    @require_tokenizers
    def    SCREAMING_SNAKE_CASE_     (					self     :						Any):


         """simple docstring"""







         a					:							str							= Tokenizer(WordPiece(unk_token='[UNK]'))
         PreTrainedTokenizerFast(tokenizer_object=UpperCAmelCase_)







    @require_tokenizers
    def    SCREAMING_SNAKE_CASE_     (					self     :						str):


         """simple docstring"""







         a					:							Tuple							= Tokenizer(WordPiece(unk_token='[UNK]'))
         with tempfile.TemporaryDirectory() as tmpdirname:
              bert_tokenizer.save(os.path.join(UpperCAmelCase_							,							'tokenizer.json'))
              PreTrainedTokenizerFast(tokenizer_file=os.path.join(UpperCAmelCase_							,							'tokenizer.json'))


'''simple docstring'''





from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCamelCase       :     Optional[Any]			=    logging.get_logger(__name__)

UpperCamelCase       :     Union[str, Any]			=    {
    """ZinengTang/tvlt-base""": """https://huggingface.co/ZinengTang/tvlt-base/blob/main/config.json""",
}



class   UpperCamelCase					(       a_       ):







    """simple docstring"""





    A     :    int				=			"tvlt"





    def __init__(					self     :						List[str]							,							UpperCAmelCase_     :						Any=2_2_4							,							UpperCAmelCase_     :						Optional[Any]=2_0_4_8							,							UpperCAmelCase_     :						Dict=1_2_8							,							UpperCAmelCase_     :						str=[1_6, 1_6]							,							UpperCAmelCase_     :						int=[1_6, 1_6]							,							UpperCAmelCase_     :						int=3							,							UpperCAmelCase_     :						Optional[int]=1							,							UpperCAmelCase_     :						List[str]=8							,							UpperCAmelCase_     :						List[Any]=7_6_8							,							UpperCAmelCase_     :						int=1_2							,							UpperCAmelCase_     :						List[Any]=1_2							,							UpperCAmelCase_     :						Optional[Any]=3_0_7_2							,							UpperCAmelCase_     :						List[str]="gelu"							,							UpperCAmelCase_     :						Tuple=0.0							,							UpperCAmelCase_     :						Optional[Any]=0.0							,							UpperCAmelCase_     :						Tuple=0.02							,							UpperCAmelCase_     :						Any=1e-6							,							UpperCAmelCase_     :						Dict=True							,							UpperCAmelCase_     :						Union[str, Any]=False							,							UpperCAmelCase_     :						Tuple=1_6							,							UpperCAmelCase_     :						str=5_1_2							,							UpperCAmelCase_     :						List[str]=8							,							UpperCAmelCase_     :						Union[str, Any]=2_0_4_8							,							UpperCAmelCase_     :						Tuple=0.75							,							UpperCAmelCase_     :						Optional[Any]=0.15							,							UpperCAmelCase_     :						Union[str, Any]="frame-level"							,							UpperCAmelCase_     :						List[str]=True							,							UpperCAmelCase_     :						Any=True							,							UpperCAmelCase_     :						Optional[int]="classification"							,							**UpperCAmelCase_     :						Any							,							):


         """simple docstring"""







         super().__init__(**UpperCAmelCase_)

         if audio_mask_type not in ("frame-level", "patch_level"):
              raise ValueError(
                  'audio_mask_type must be one of two acceptable strategies - {\'frame_level\', \'patch-level\') '
                  f"""got {audio_mask_type}""")

         a					:							str							= image_size
         a					:							List[Any]							= spectrogram_length
         a					:							Union[str, Any]							= frequency_length
         a					:							str							= image_patch_size
         a					:							Dict							= audio_patch_size
         a					:							Dict							= num_image_channels
         a					:							Tuple							= num_audio_channels
         a					:							Optional[int]							= num_frames

         a					:							str							= hidden_size
         a					:							List[Any]							= num_hidden_layers
         a					:							Optional[Any]							= num_attention_heads
         a					:							Any							= intermediate_size
         a					:							List[Any]							= hidden_act
         a					:							int							= hidden_dropout_prob
         a					:							Optional[Any]							= attention_probs_dropout_prob
         a					:							Optional[Any]							= initializer_range
         a					:							List[str]							= layer_norm_eps
         a					:							List[Any]							= qkv_bias
         a					:							Dict							= use_mean_pooling

         a					:							List[Any]							= decoder_num_attention_heads
         a					:							Any							= decoder_hidden_size
         a					:							int							= decoder_num_hidden_layers
         a					:							Tuple							= decoder_intermediate_size
         a					:							Tuple							= pixel_mask_ratio
         a					:							List[Any]							= audio_mask_ratio
         a					:							Optional[Any]							= audio_mask_type

         a					:							Any							= task_matching
         a					:							Optional[Any]							= task_mae
         a					:							List[str]							= loss_type

