




import copy
import os
from typing import Union

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


_lowerCamelCase      :						Union[str, Any]							=  logging.get_logger(__name__)

_lowerCamelCase      :						List[str]							=  {
    """google/pix2struct-textcaps-base""": (
        """https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json"""
    ),
}


class 							UpperCamelCase_       (					UpperCAmelCase__	):

    '''simple docstring'''






    UpperCAmelCase__				    = '''pix2struct_text_model'''
    UpperCAmelCase__				    = ['''past_key_values''']
    UpperCAmelCase__				    = {
        '''hidden_size''': '''hidden_size''',
        '''num_attention_heads''': '''num_heads''',
        '''num_hidden_layers''': '''num_layers''',
    }


    def __init__(     self :      Dict   ,					UpperCAmelCase__ :      Any=50_244   ,					UpperCAmelCase__ :      Tuple=768   ,					UpperCAmelCase__ :      Union[str, Any]=64   ,					UpperCAmelCase__ :      Union[str, Any]=2_048   ,					UpperCAmelCase__ :      List[str]=12   ,					UpperCAmelCase__ :      Any=12   ,					UpperCAmelCase__ :      int=32   ,					UpperCAmelCase__ :      Optional[int]=128   ,					UpperCAmelCase__ :      str=0.1   ,					UpperCAmelCase__ :      List[str]=1e-6   ,					UpperCAmelCase__ :      Dict=1.0   ,					UpperCAmelCase__ :      Any="gelu_new"   ,					UpperCAmelCase__ :      Dict=0   ,					UpperCAmelCase__ :      Union[str, Any]=False   ,					UpperCAmelCase__ :      int=0   ,					UpperCAmelCase__ :      List[str]=1   ,					UpperCAmelCase__ :      str=False   ,					UpperCAmelCase__ :      Any=True   ,					**UpperCAmelCase__ :      Union[str, Any]   ,					)		->Union[str, Any]:





           '''simple docstring'''

           A__ 					=       vocab_size
           A__ 					=       hidden_size
           A__ 					=       d_kv
           A__ 					=       d_ff
           A__ 					=       num_layers
           A__ 					=       num_heads
           A__ 					=       relative_attention_num_buckets
           A__ 					=       relative_attention_max_distance
           A__ 					=       dropout_rate
           A__ 					=       layer_norm_epsilon
           A__ 					=       initializer_factor
           A__ 					=       use_cache

           A__ 					=       eos_token_id
           A__ 					=       decoder_start_token_id

           # for backwards compatibility
           A__ 					=       dense_act_fn

           super().__init__(
               pad_token_id=UpperCAmelCase__   ,					eos_token_id=UpperCAmelCase__   ,					decoder_start_token_id=UpperCAmelCase__   ,					tie_word_embeddings=UpperCAmelCase__   ,					is_decoder=UpperCAmelCase__   ,					**UpperCAmelCase__   ,					)





    @classmethod
    def 			SCREAMING_SNAKE_CASE				(     cls :      Optional[Any]   ,					UpperCAmelCase__ :      Union[str, os.PathLike]   ,					**UpperCAmelCase__ :      Any)		->"PretrainedConfig":





           '''simple docstring'''

           cls._set_token_in_kwargs(UpperCAmelCase__)

           A__					,				A__ 					=       cls.get_config_dict(UpperCAmelCase__   ,					**UpperCAmelCase__)

           # get the text config dict if we are loading from Pix2StructConfig
           if config_dict.get('''model_type''') == "pix2struct":
                  A__ 					=       config_dict['''text_config''']

           if "model_type" in config_dict and hasattr(cls   ,					'''model_type''') and config_dict["model_type"] != cls.model_type:
                  logger.warning(
                      f"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """
                      f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""")

           return cls.from_dict(UpperCAmelCase__   ,					**UpperCAmelCase__)


class 							UpperCamelCase_       (					UpperCAmelCase__	):

    '''simple docstring'''






    UpperCAmelCase__				    = '''pix2struct_vision_model'''


    def __init__(     self :      Optional[Any]   ,					UpperCAmelCase__ :      Any=768   ,					UpperCAmelCase__ :      int=768   ,					UpperCAmelCase__ :      int=2_048   ,					UpperCAmelCase__ :      int=64   ,					UpperCAmelCase__ :      Optional[Any]=12   ,					UpperCAmelCase__ :      int=12   ,					UpperCAmelCase__ :      List[Any]="gelu_new"   ,					UpperCAmelCase__ :      Union[str, Any]=1e-6   ,					UpperCAmelCase__ :      Dict=0.0   ,					UpperCAmelCase__ :      List[Any]=0.0   ,					UpperCAmelCase__ :      Any=1e-10   ,					UpperCAmelCase__ :      Any=1.0   ,					UpperCAmelCase__ :      Optional[int]=4_096   ,					UpperCAmelCase__ :      Dict=32   ,					UpperCAmelCase__ :      int=128   ,					**UpperCAmelCase__ :      Dict   ,					)		->Optional[Any]:





           '''simple docstring'''

           super().__init__(**UpperCAmelCase__)

           A__ 					=       hidden_size
           A__ 					=       patch_embed_hidden_size
           A__ 					=       d_ff
           A__ 					=       dropout_rate
           A__ 					=       num_hidden_layers
           A__ 					=       num_attention_heads
           A__ 					=       initializer_range
           A__ 					=       initializer_factor
           A__ 					=       attention_dropout
           A__ 					=       layer_norm_eps
           A__ 					=       dense_act_fn
           A__ 					=       seq_len
           A__ 					=       relative_attention_num_buckets
           A__ 					=       relative_attention_max_distance
           A__ 					=       d_kv





    @classmethod
    def 			SCREAMING_SNAKE_CASE				(     cls :      Tuple   ,					UpperCAmelCase__ :      Union[str, os.PathLike]   ,					**UpperCAmelCase__ :      Tuple)		->"PretrainedConfig":





           '''simple docstring'''

           cls._set_token_in_kwargs(UpperCAmelCase__)

           A__					,				A__ 					=       cls.get_config_dict(UpperCAmelCase__   ,					**UpperCAmelCase__)

           # get the vision config dict if we are loading from Pix2StructConfig
           if config_dict.get('''model_type''') == "pix2struct":
                  A__ 					=       config_dict['''vision_config''']

           if "model_type" in config_dict and hasattr(cls   ,					'''model_type''') and config_dict["model_type"] != cls.model_type:
                  logger.warning(
                      f"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """
                      f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""")

           return cls.from_dict(UpperCAmelCase__   ,					**UpperCAmelCase__)


class 							UpperCamelCase_       (					UpperCAmelCase__	):

    '''simple docstring'''






    UpperCAmelCase__				    = '''pix2struct'''
    UpperCAmelCase__				    = True


    def __init__(     self :      List[str]   ,					UpperCAmelCase__ :      Union[str, Any]=None   ,					UpperCAmelCase__ :      Tuple=None   ,					UpperCAmelCase__ :      str=1.0   ,					UpperCAmelCase__ :      Optional[int]=0.02   ,					UpperCAmelCase__ :      List[Any]=False   ,					UpperCAmelCase__ :      List[Any]=False   ,					UpperCAmelCase__ :      Dict=True   ,					**UpperCAmelCase__ :      List[Any]   ,					)		->Union[str, Any]:





           '''simple docstring'''

           super().__init__(tie_word_embeddings=UpperCAmelCase__   ,					is_encoder_decoder=UpperCAmelCase__   ,					**UpperCAmelCase__)

           if text_config is None:
                  A__ 					=       {}
                  logger.info('''text_config is None. Initializing the Pix2StructTextConfig with default values.''')

           if vision_config is None:
                  A__ 					=       {}
                  logger.info('''vision_config is None. Initializing the Pix2StructVisionConfig with default values.''')

           A__ 					=       PixaStructTextConfig(**UpperCAmelCase__)
           A__ 					=       PixaStructVisionConfig(**UpperCAmelCase__)

           A__ 					=       self.text_config.decoder_start_token_id
           A__ 					=       self.text_config.pad_token_id
           A__ 					=       self.text_config.eos_token_id

           A__ 					=       initializer_factor
           A__ 					=       initializer_range

           A__ 					=       self.initializer_range
           A__ 					=       self.initializer_range

           A__ 					=       is_vqa


    @classmethod
    def 			SCREAMING_SNAKE_CASE				(     cls :      Optional[Any]   ,					UpperCAmelCase__ :      PixaStructTextConfig   ,					UpperCAmelCase__ :      PixaStructVisionConfig   ,					**UpperCAmelCase__ :      Dict)		->Tuple:





           '''simple docstring'''

           return cls(text_config=text_config.to_dict()   ,					vision_config=vision_config.to_dict()   ,					**UpperCAmelCase__)





    def 			SCREAMING_SNAKE_CASE				(     self :      List[Any])		->List[str]:





           '''simple docstring'''

           A__ 					=       copy.deepcopy(self.__dict__)
           A__ 					=       self.text_config.to_dict()
           A__ 					=       self.vision_config.to_dict()
           A__ 					=       self.__class__.model_type
           return output







import os
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from huggingface_hub.file_download import http_get
from requests.exceptions import HTTPError

from transformers import (
    AlbertTokenizer,
    AutoTokenizer,
    BertTokenizer,
    BertTokenizerFast,
    GPTaTokenizerFast,
    is_tokenizers_available,
)
from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers
from transformers.tokenization_utils import Trie


sys.path.append(str(Path(__file__).parent.parent / 'utils'))

from test_module.custom_tokenization import CustomTokenizer  # noqa E402


if is_tokenizers_available():
				from test_module.custom_tokenization_fast import CustomTokenizerFast



class        lowerCAmelCase__					(  unittest.TestCase       ):


				def __UpperCamelCase						(							self      :  Any       )		->     Tuple:
											# A mock response for an HTTP head request to emulate server down
											A      						=    mock.Mock()
											A      						=    500
											A      						=    {}
											A      						=    HTTPError
											A      						=    {}

											# Download this model to make sure it's in the cache.
											A      						=    BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert'       )

											# Under the mock environment we get a 500 error when trying to reach the tokenizer.
											with mock.patch('requests.Session.request'						, return_value=__UpperCamelCase       ) as mock_head:
																		A      						=    BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert'       )
																		# This check we did call the fake head request
																		mock_head.assert_called()


				@require_tokenizers
				def __UpperCamelCase						(							self      :  Union[str, Any]       )		->     Union[str, Any]:
											# A mock response for an HTTP head request to emulate server down
											A      						=    mock.Mock()
											A      						=    500
											A      						=    {}
											A      						=    HTTPError
											A      						=    {}

											# Download this model to make sure it's in the cache.
											A      						=    GPTaTokenizerFast.from_pretrained('gpt2'       )

											# Under the mock environment we get a 500 error when trying to reach the tokenizer.
											with mock.patch('requests.Session.request'						, return_value=__UpperCamelCase       ) as mock_head:
																		A      						=    GPTaTokenizerFast.from_pretrained('gpt2'       )
																		# This check we did call the fake head request
																		mock_head.assert_called()


				def __UpperCamelCase						(							self      :  Optional[Any]       )		->     List[str]:
											# This test is for deprecated behavior and can be removed in v5
											try:
																		A      						=    tempfile.mktemp()
																		with open(__UpperCamelCase						, 'wb'       ) as f:
																									http_get('https://huggingface.co/albert-base-v1/resolve/main/spiece.model'						, __UpperCamelCase       )

																		A      						=    AlbertTokenizer.from_pretrained(__UpperCamelCase       )
											finally:
																		os.remove(__UpperCamelCase       )

											# Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in
											# the current folder and have the right name.
											if os.path.isfile('tokenizer.json'       ):
																		# We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it.
																		return
											try:
																		with open('tokenizer.json'						, 'wb'       ) as f:
																									http_get('https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json'						, __UpperCamelCase       )
																		A      						=    AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2'       )
																		# The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000
																		self.assertEqual(tokenizer.vocab_size						, 1_000       )
																		# Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file.

											finally:
																		os.remove('tokenizer.json'       )


				def __UpperCamelCase						(							self      :  str       )		->     int:
											# This test is for deprecated behavior and can be removed in v5
											A      						=    AlbertTokenizer.from_pretrained('https://huggingface.co/albert-base-v1/resolve/main/spiece.model'       )





@is_staging_test
class        lowerCAmelCase__					(  unittest.TestCase       ):
				A_   :     str								=     ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou']


				@classmethod
				def __UpperCamelCase						(							cls      :  Tuple       )		->     Dict:
											A      						=    TOKEN
											HfFolder.save_token(__UpperCamelCase       )


				@classmethod
				def __UpperCamelCase						(							cls      :  Any       )		->     Dict:
											try:
																		delete_repo(token=cls._token						, repo_id='test-tokenizer'       )
											except HTTPError:
																		pass

											try:
																		delete_repo(token=cls._token						, repo_id='valid_org/test-tokenizer-org'       )
											except HTTPError:
																		pass

											try:
																		delete_repo(token=cls._token						, repo_id='test-dynamic-tokenizer'       )
											except HTTPError:
																		pass


				def __UpperCamelCase						(							self      :  Optional[Any]       )		->     List[str]:
											with tempfile.TemporaryDirectory() as tmp_dir:
																		A      						=    os.path.join(__UpperCamelCase						, 'vocab.txt'       )
																		with open(__UpperCamelCase						, 'w'						, encoding='utf-8'       ) as vocab_writer:
																									vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens]       )       )
																		A      						=    BertTokenizer(__UpperCamelCase       )

											tokenizer.push_to_hub('test-tokenizer'						, use_auth_token=self._token       )
											A      						=    BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer'''       )
											self.assertDictEqual(new_tokenizer.vocab						, tokenizer.vocab       )

											# Reset repo
											delete_repo(token=self._token						, repo_id='test-tokenizer'       )

											# Push to hub via save_pretrained
											with tempfile.TemporaryDirectory() as tmp_dir:
																		tokenizer.save_pretrained(__UpperCamelCase						, repo_id='test-tokenizer'						, push_to_hub=__UpperCamelCase						, use_auth_token=self._token       )

											A      						=    BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer'''       )
											self.assertDictEqual(new_tokenizer.vocab						, tokenizer.vocab       )


				def __UpperCamelCase						(							self      :  List[str]       )		->     Tuple:
											with tempfile.TemporaryDirectory() as tmp_dir:
																		A      						=    os.path.join(__UpperCamelCase						, 'vocab.txt'       )
																		with open(__UpperCamelCase						, 'w'						, encoding='utf-8'       ) as vocab_writer:
																									vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens]       )       )
																		A      						=    BertTokenizer(__UpperCamelCase       )

											tokenizer.push_to_hub('valid_org/test-tokenizer-org'						, use_auth_token=self._token       )
											A      						=    BertTokenizer.from_pretrained('valid_org/test-tokenizer-org'       )
											self.assertDictEqual(new_tokenizer.vocab						, tokenizer.vocab       )

											# Reset repo
											delete_repo(token=self._token						, repo_id='valid_org/test-tokenizer-org'       )

											# Push to hub via save_pretrained
											with tempfile.TemporaryDirectory() as tmp_dir:
																		tokenizer.save_pretrained(
																		    __UpperCamelCase						, repo_id='valid_org/test-tokenizer-org'						, push_to_hub=__UpperCamelCase						, use_auth_token=self._token       )

											A      						=    BertTokenizer.from_pretrained('valid_org/test-tokenizer-org'       )
											self.assertDictEqual(new_tokenizer.vocab						, tokenizer.vocab       )


				@require_tokenizers
				def __UpperCamelCase						(							self      :  Any       )		->     Union[str, Any]:
											CustomTokenizer.register_for_auto_class()
											with tempfile.TemporaryDirectory() as tmp_dir:
																		A      						=    os.path.join(__UpperCamelCase						, 'vocab.txt'       )
																		with open(__UpperCamelCase						, 'w'						, encoding='utf-8'       ) as vocab_writer:
																									vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens]       )       )
																		A      						=    CustomTokenizer(__UpperCamelCase       )

											# No fast custom tokenizer
											tokenizer.push_to_hub('test-dynamic-tokenizer'						, use_auth_token=self._token       )

											A      						=    AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer'''						, trust_remote_code=__UpperCamelCase       )
											# Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module
											self.assertEqual(tokenizer.__class__.__name__						, 'CustomTokenizer'       )

											# Fast and slow custom tokenizer
											CustomTokenizerFast.register_for_auto_class()
											with tempfile.TemporaryDirectory() as tmp_dir:
																		A      						=    os.path.join(__UpperCamelCase						, 'vocab.txt'       )
																		with open(__UpperCamelCase						, 'w'						, encoding='utf-8'       ) as vocab_writer:
																									vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens]       )       )

																		A      						=    BertTokenizerFast.from_pretrained(__UpperCamelCase       )
																		bert_tokenizer.save_pretrained(__UpperCamelCase       )
																		A      						=    CustomTokenizerFast.from_pretrained(__UpperCamelCase       )

											tokenizer.push_to_hub('test-dynamic-tokenizer'						, use_auth_token=self._token       )

											A      						=    AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer'''						, trust_remote_code=__UpperCamelCase       )
											# Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
											self.assertEqual(tokenizer.__class__.__name__						, 'CustomTokenizerFast'       )
											A      						=    AutoTokenizer.from_pretrained(
											    f'''{USER}/test-dynamic-tokenizer'''						, use_fast=__UpperCamelCase						, trust_remote_code=__UpperCamelCase       )
											# Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
											self.assertEqual(tokenizer.__class__.__name__						, 'CustomTokenizer'       )





class        lowerCAmelCase__					(  unittest.TestCase       ):


				def __UpperCamelCase						(							self      :  List[Any]       )		->     Any:
											A      						=    Trie()
											trie.add('Hello 友達'       )
											self.assertEqual(trie.data						, {'H': {'e': {'l': {'l': {'o': {' ': {'友': {'達': {'': 1}}}}}}}}}       )
											trie.add('Hello'       )
											trie.data
											self.assertEqual(trie.data						, {'H': {'e': {'l': {'l': {'o': {'': 1, ' ': {'友': {'達': {'': 1}}}}}}}}}       )


				def __UpperCamelCase						(							self      :  Dict       )		->     Tuple:
											A      						=    Trie()
											self.assertEqual(trie.split('[CLS] This is a extra_id_100'       )						, ['[CLS] This is a extra_id_100']       )
											trie.add('[CLS]'       )
											trie.add('extra_id_1'       )
											trie.add('extra_id_100'       )
											self.assertEqual(trie.split('[CLS] This is a extra_id_100'       )						, ['[CLS]', ' This is a ', 'extra_id_100']       )


				def __UpperCamelCase						(							self      :  Any       )		->     Optional[int]:
											A      						=    Trie()
											trie.add('A'       )
											self.assertEqual(trie.split('ABC'       )						, ['A', 'BC']       )
											self.assertEqual(trie.split('BCA'       )						, ['BC', 'A']       )


				def __UpperCamelCase						(							self      :  Union[str, Any]       )		->     str:
											A      						=    Trie()
											trie.add('TOKEN]'       )
											trie.add('[SPECIAL_TOKEN]'       )
											self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]'       )						, ['This is something ', '[SPECIAL_TOKEN]']       )


				def __UpperCamelCase						(							self      :  Union[str, Any]       )		->     Tuple:
											A      						=    Trie()
											trie.add('A'       )
											trie.add('P'       )
											trie.add('[SPECIAL_TOKEN]'       )
											self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]'       )						, ['This is something ', '[SPECIAL_TOKEN]']       )


				def __UpperCamelCase						(							self      :  List[str]       )		->     Tuple:
											A      						=    Trie()
											trie.add('AB'       )
											trie.add('B'       )
											trie.add('C'       )
											self.assertEqual(trie.split('ABC'       )						, ['AB', 'C']       )


				def __UpperCamelCase						(							self      :  Union[str, Any]       )		->     List[Any]:
											A      						=    Trie()
											trie.add('ABC'       )
											trie.add('B'       )
											trie.add('CD'       )
											self.assertEqual(trie.split('ABCD'       )						, ['ABC', 'D']       )


				def __UpperCamelCase						(							self      :  Union[str, Any]       )		->     List[Any]:
											# Even if the offsets are wrong, we necessarily output correct string
											# parts.
											A      						=    Trie()
											A      						=    trie.cut_text('ABC'						, [0, 0, 2, 1, 2, 3]       )
											self.assertEqual(__UpperCamelCase						, ['AB', 'C']       )