


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 A    (  unittest.TestCase	):






      def 			lowerCamelCase			(   self		:	List[str]					)   ->		Any:
             """simple docstring"""




             _lowerCamelCase			:						Optional[Any]            =tempfile.mkdtemp()

             # fmt: off
             _lowerCamelCase			:						int            =['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest']
             # fmt: on
             _lowerCamelCase			:						Any            =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]					)					)

             _lowerCamelCase			:						List[Any]            ={
                 '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],
             }
             _lowerCamelCase			:						Dict            =os.path.join(self.tmpdirname     ,  lowercase_					)
             with open(self.image_processor_file     ,  'w'     ,  encoding='utf-8'					) as fp:
                    json.dump(lowercase_     ,  lowercase_					)






      def 			lowerCamelCase			(   self		:	List[str]     ,  **lowercase_		:	Dict					)   ->		str:
             """simple docstring"""




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






      def 			lowerCamelCase			(   self		:	Any     ,  **lowercase_		:	int					)   ->		Optional[Any]:
             """simple docstring"""




             return ViTImageProcessor.from_pretrained(self.tmpdirname     ,  **lowercase_					)






      def 			lowerCamelCase			(   self		:	Tuple					)   ->		Optional[Any]:
             """simple docstring"""




             shutil.rmtree(self.tmpdirname					)






      def 			lowerCamelCase			(   self		:	Union[str, Any]					)   ->		Dict:
             """simple docstring"""




             _lowerCamelCase			:						str            =[np.random.randint(255     ,  size=(3, 30, 400)     ,  dtype=np.uinta					)]

             _lowerCamelCase			:						Optional[Any]            =[Image.fromarray(np.moveaxis(lowercase_     ,  0     ,  -1					)					) for x in image_inputs]

             return image_inputs






      def 			lowerCamelCase			(   self		:	Union[str, Any]					)   ->		Dict:
             """simple docstring"""




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

             _lowerCamelCase			:						List[str]            =VisionTextDualEncoderProcessor(tokenizer=lowercase_     ,  image_processor=lowercase_					)

             processor.save_pretrained(self.tmpdirname					)
             _lowerCamelCase			:						int            =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     ,  lowercase_					)






      def 			lowerCamelCase			(   self		:	Any					)   ->		Union[str, Any]:
             """simple docstring"""




             _lowerCamelCase			:						Dict            =VisionTextDualEncoderProcessor(
                 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			:						str            =self.get_image_processor(do_normalize=lowercase_     ,  padding_value=1.0					)

             _lowerCamelCase			:						Dict            =VisionTextDualEncoderProcessor.from_pretrained(
                 self.tmpdirname     ,  bos_token='(BOS)'     ,  eos_token='(EOS)'     ,  do_normalize=lowercase_     ,  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     ,  lowercase_					)






      def 			lowerCamelCase			(   self		:	Any					)   ->		int:
             """simple docstring"""




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

             _lowerCamelCase			:						str            =VisionTextDualEncoderProcessor(tokenizer=lowercase_     ,  image_processor=lowercase_					)

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

             _lowerCamelCase			:						Any            =image_processor(lowercase_     ,  return_tensors='np'					)
             _lowerCamelCase			:						List[Any]            =processor(images=lowercase_     ,  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 			lowerCamelCase			(   self		:	Dict					)   ->		str:
             """simple docstring"""




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

             _lowerCamelCase			:						str            =VisionTextDualEncoderProcessor(tokenizer=lowercase_     ,  image_processor=lowercase_					)

             _lowerCamelCase			:						Any            ='lower newer'

             _lowerCamelCase			:						Optional[int]            =processor(text=lowercase_					)

             _lowerCamelCase			:						int            =tokenizer(lowercase_					)

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






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




             _lowerCamelCase			:						Tuple            =self.get_image_processor()
             _lowerCamelCase			:						int            =self.get_tokenizer()

             _lowerCamelCase			:						List[Any]            =VisionTextDualEncoderProcessor(tokenizer=lowercase_     ,  image_processor=lowercase_					)

             _lowerCamelCase			:						str            ='lower newer'
             _lowerCamelCase			:						Optional[Any]            =self.prepare_image_inputs()

             _lowerCamelCase			:						Optional[Any]            =processor(text=lowercase_     ,  images=lowercase_					)

             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(lowercase_					):
                    processor()






      def 			lowerCamelCase			(   self		:	Dict					)   ->		Dict:
             """simple docstring"""




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

             _lowerCamelCase			:						Dict            =VisionTextDualEncoderProcessor(tokenizer=lowercase_     ,  image_processor=lowercase_					)

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

             _lowerCamelCase			:						Optional[int]            =processor.batch_decode(lowercase_					)
             _lowerCamelCase			:						List[Any]            =tokenizer.batch_decode(lowercase_					)

             self.assertListEqual(lowercase_     ,  lowercase_					)






      def 			lowerCamelCase			(   self		:	Any					)   ->		Dict:
             """simple docstring"""




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

             _lowerCamelCase			:						List[str]            =VisionTextDualEncoderProcessor(tokenizer=lowercase_     ,  image_processor=lowercase_					)

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

             _lowerCamelCase			:						Optional[Any]            =processor(text=lowercase_     ,  images=lowercase_					)

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






from timeit import timeit

lowerCamelCase		   =			{
    'MALAYALAM': True,
    'String': False,
    'rotor': True,
    'level': True,
    'A': True,
    'BB': True,
    'ABC': False,
    'amanaplanacanalpanama': True,  # "a man a plan a canal panama"
}
# Ensure our test data is valid
assert all((key == key[::-1]) is value for key, value in test_data.items())




def       a_ (       SCREAMING_SNAKE_CASE__   : str	):
       '''simple docstring'''





       _lowerCamelCase			:						Optional[int]            =0
       _lowerCamelCase			:						Union[str, Any]            =len(SCREAMING_SNAKE_CASE__	) - 1
       while start_i < end_i:
              if s[start_i] == s[end_i]:
                     start_i += 1
                     end_i -= 1
              else:
                     return False
       return True




def       a_ (       SCREAMING_SNAKE_CASE__   : str	):
       '''simple docstring'''





       _lowerCamelCase			:						List[str]            =len(SCREAMING_SNAKE_CASE__	) // 2
       _lowerCamelCase			:						Optional[Any]            =len(SCREAMING_SNAKE_CASE__	)

       # We need to traverse till half of the length of string
       # as we can get access of the i'th last element from
       # i'th index.
       # eg: [0,1,2,3,4,5] => 4th index can be accessed
       # with the help of 1st index (i==n-i-1)
       # where n is length of string
       return all(s[i] == s[n - i - 1] for i in range(SCREAMING_SNAKE_CASE__	)	)




def       a_ (       SCREAMING_SNAKE_CASE__   : str	):
       '''simple docstring'''





       if len(SCREAMING_SNAKE_CASE__	) <= 2:
              return True
       if s[0] == s[len(SCREAMING_SNAKE_CASE__	) - 1]:
              return is_palindrome_recursive(s[1:-1]	)
       else:
              return False




def       a_ (       SCREAMING_SNAKE_CASE__   : str	):
       '''simple docstring'''





       return s == s[::-1]




def       a_ (       SCREAMING_SNAKE_CASE__   : str	):
       '''simple docstring'''





       _lowerCamelCase			:						Optional[int]            =F'''all({name}(key) is value for key, value in test_data.items())'''
       _lowerCamelCase			:						List[Any]            =F'''from __main__ import test_data, {name}'''
       _lowerCamelCase			:						Any            =500_000
       _lowerCamelCase			:						Dict            =timeit(stmt=SCREAMING_SNAKE_CASE__						,     setup=SCREAMING_SNAKE_CASE__						,     number=SCREAMING_SNAKE_CASE__	)
       print(F'''{name:<35} finished {number:,} runs in {result:.5f} seconds'''	)


if __name__ == "__main__":
 for key, value in test_data.items():
  assert is_palindrome(key) is is_palindrome_recursive(key)
  assert is_palindrome(key) is is_palindrome_slice(key)
  print(F"""{key:21} {value}""")
 print('a man a plan a canal panama')

 # finished 500,000 runs in 0.46793 seconds
 benchmark_function('is_palindrome_slice')
 # finished 500,000 runs in 0.85234 seconds
 benchmark_function('is_palindrome')
 # finished 500,000 runs in 1.32028 seconds
 benchmark_function('is_palindrome_recursive')
 # finished 500,000 runs in 2.08679 seconds
 benchmark_function('is_palindrome_traversal')


