



'''simple docstring'''



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


SCREAMING_SNAKE_CASE						=	logging.get_logger(__name__)

SCREAMING_SNAKE_CASE						=	{
    'microsoft/trocr-base-handwritten': (
        'https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json'
    ),
    # See all TrOCR models at https://huggingface.co/models?filter=trocr
}
class UpperCAmelCase_					(    _UpperCAmelCase				):




      """simple docstring"""




      UpperCamelCase_								=			"""trocr"""
      UpperCamelCase_								=			["""past_key_values"""]
      UpperCamelCase_								=			{
          """num_attention_heads""": """decoder_attention_heads""",
          """hidden_size""": """d_model""",
          """num_hidden_layers""": """decoder_layers""",
      }






      def __init__( self			:		Optional[int]     ,      UpperCAmelCase			:		List[Any]=5_0265     ,      UpperCAmelCase			:		Tuple=1024     ,      UpperCAmelCase			:		List[Any]=12     ,      UpperCAmelCase			:		Union[str, Any]=16     ,      UpperCAmelCase			:		Any=4096     ,      UpperCAmelCase			:		Dict="gelu"     ,      UpperCAmelCase			:		Optional[Any]=512     ,      UpperCAmelCase			:		Optional[Any]=0.1     ,      UpperCAmelCase			:		str=0.0     ,      UpperCAmelCase			:		Dict=0.0     ,      UpperCAmelCase			:		Tuple=2     ,      UpperCAmelCase			:		int=0.0_2     ,      UpperCAmelCase			:		str=0.0     ,      UpperCAmelCase			:		int=True     ,      UpperCAmelCase			:		Any=False     ,      UpperCAmelCase			:		Tuple=True     ,      UpperCAmelCase			:		Dict=True     ,      UpperCAmelCase			:		List[Any]=1     ,      UpperCAmelCase			:		Dict=0     ,      UpperCAmelCase			:		Dict=2     ,      **UpperCAmelCase			:		Tuple     ,      )  ->  Dict:


       '''simple docstring'''

       lowercase					:   Union[str, Any]				  =vocab_size
       lowercase					:   int				  =d_model
       lowercase					:   Any				  =decoder_layers
       lowercase					:   str				  =decoder_attention_heads
       lowercase					:   Optional[Any]				  =decoder_ffn_dim
       lowercase					:   str				  =activation_function
       lowercase					:   Dict				  =max_position_embeddings
       lowercase					:   Dict				  =dropout
       lowercase					:   Optional[int]				  =attention_dropout
       lowercase					:   Dict				  =activation_dropout
       lowercase					:   Tuple				  =init_std
       lowercase					:   Optional[int]				  =decoder_layerdrop
       lowercase					:   Optional[int]				  =use_cache
       lowercase					:   Union[str, Any]				  =scale_embedding
       lowercase					:   Optional[Any]				  =use_learned_position_embeddings
       lowercase					:   Dict				  =layernorm_embedding

       super().__init__(
           pad_token_id=lowercase__     ,      bos_token_id=lowercase__     ,      eos_token_id=lowercase__     ,      decoder_start_token_id=lowercase__     ,      **lowercase__     ,      )











'''simple docstring'''



import subprocess
import sys

from transformers import BertConfig, BertModel, BertTokenizer, pipeline
from transformers.testing_utils import TestCasePlus, require_torch
class UpperCAmelCase_					(    __A				):




      """simple docstring"""




      @require_torch
      def 				A__      ( self			:		Tuple		)  ->  Optional[int]:


       '''simple docstring'''

       lowercase					:   Any				  ='''
from transformers import BertConfig, BertModel, BertTokenizer, pipeline
        '''

       lowercase					:   Optional[int]				  ='''
mname = "hf-internal-testing/tiny-random-bert"
BertConfig.from_pretrained(mname)
BertModel.from_pretrained(mname)
BertTokenizer.from_pretrained(mname)
pipe = pipeline(task="fill-mask", model=mname)
print("success")
        '''

       lowercase					:   Any				  ='''
import socket
def offline_socket(*args, **kwargs): raise RuntimeError("Offline mode is enabled, we shouldn\'t access internet")
socket.socket = offline_socket
        '''

       # Force fetching the files so that we can use the cache
       lowercase					:   Tuple				  ='''hf-internal-testing/tiny-random-bert'''
       BertConfig.from_pretrained(UpperCAmelCase		)
       BertModel.from_pretrained(UpperCAmelCase		)
       BertTokenizer.from_pretrained(UpperCAmelCase		)
       pipeline(task='''fill-mask'''     ,      model=UpperCAmelCase		)

       # baseline - just load from_pretrained with normal network
       lowercase					:   List[str]				  =[sys.executable, '''-c''', '''\n'''.join([load, run, mock]		)]

       # should succeed
       lowercase					:   Tuple				  =self.get_env()
       # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
       lowercase					:   Optional[Any]				  ='''1'''
       lowercase					:   Any				  =subprocess.run(UpperCAmelCase     ,      env=UpperCAmelCase     ,      check=UpperCAmelCase     ,      capture_output=UpperCAmelCase		)
       self.assertEqual(result.returncode     ,      0     ,      result.stderr		)
       self.assertIn('''success'''     ,      result.stdout.decode()		)






      @require_torch
      def 				A__      ( self			:		str		)  ->  List[str]:


       '''simple docstring'''

       lowercase					:   str				  ='''
from transformers import BertConfig, BertModel, BertTokenizer, pipeline
        '''

       lowercase					:   Optional[Any]				  ='''
mname = "hf-internal-testing/tiny-random-bert"
BertConfig.from_pretrained(mname)
BertModel.from_pretrained(mname)
BertTokenizer.from_pretrained(mname)
pipe = pipeline(task="fill-mask", model=mname)
print("success")
        '''

       lowercase					:   Optional[int]				  ='''
import socket
def offline_socket(*args, **kwargs): raise socket.error("Faking flaky internet")
socket.socket = offline_socket
        '''

       # Force fetching the files so that we can use the cache
       lowercase					:   Optional[Any]				  ='''hf-internal-testing/tiny-random-bert'''
       BertConfig.from_pretrained(UpperCAmelCase		)
       BertModel.from_pretrained(UpperCAmelCase		)
       BertTokenizer.from_pretrained(UpperCAmelCase		)
       pipeline(task='''fill-mask'''     ,      model=UpperCAmelCase		)

       # baseline - just load from_pretrained with normal network
       lowercase					:   Optional[Any]				  =[sys.executable, '''-c''', '''\n'''.join([load, run, mock]		)]

       # should succeed
       lowercase					:   str				  =self.get_env()
       lowercase					:   Any				  =subprocess.run(UpperCAmelCase     ,      env=UpperCAmelCase     ,      check=UpperCAmelCase     ,      capture_output=UpperCAmelCase		)
       self.assertEqual(result.returncode     ,      0     ,      result.stderr		)
       self.assertIn('''success'''     ,      result.stdout.decode()		)






      @require_torch
      def 				A__      ( self			:		Any		)  ->  Optional[Any]:


       '''simple docstring'''

       lowercase					:   Optional[Any]				  ='''
from transformers import BertConfig, BertModel, BertTokenizer
        '''

       lowercase					:   List[Any]				  ='''
mname = "hf-internal-testing/tiny-random-bert-sharded"
BertConfig.from_pretrained(mname)
BertModel.from_pretrained(mname)
print("success")
        '''

       lowercase					:   int				  ='''
import socket
def offline_socket(*args, **kwargs): raise ValueError("Offline mode is enabled")
socket.socket = offline_socket
        '''

       # baseline - just load from_pretrained with normal network
       lowercase					:   Tuple				  =[sys.executable, '''-c''', '''\n'''.join([load, run]		)]

       # should succeed
       lowercase					:   Optional[Any]				  =self.get_env()
       lowercase					:   List[Any]				  =subprocess.run(UpperCAmelCase     ,      env=UpperCAmelCase     ,      check=UpperCAmelCase     ,      capture_output=UpperCAmelCase		)
       self.assertEqual(result.returncode     ,      0     ,      result.stderr		)
       self.assertIn('''success'''     ,      result.stdout.decode()		)

       # next emulate no network
       lowercase					:   Tuple				  =[sys.executable, '''-c''', '''\n'''.join([load, mock, run]		)]

       # Doesn't fail anymore since the model is in the cache due to other tests, so commenting this.
       # env["TRANSFORMERS_OFFLINE"] = "0"
       # result = subprocess.run(cmd, env=env, check=False, capture_output=True)
       # self.assertEqual(result.returncode, 1, result.stderr)

       # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
       lowercase					:   Any				  ='''1'''
       lowercase					:   Optional[Any]				  =subprocess.run(UpperCAmelCase     ,      env=UpperCAmelCase     ,      check=UpperCAmelCase     ,      capture_output=UpperCAmelCase		)
       self.assertEqual(result.returncode     ,      0     ,      result.stderr		)
       self.assertIn('''success'''     ,      result.stdout.decode()		)






      @require_torch
      def 				A__      ( self			:		Tuple		)  ->  Optional[int]:


       '''simple docstring'''

       lowercase					:   Optional[int]				  ='''
from transformers import pipeline
        '''
       lowercase					:   List[Any]				  ='''
mname = "hf-internal-testing/tiny-random-bert"
pipe = pipeline(model=mname)
        '''

       lowercase					:   Tuple				  ='''
import socket
def offline_socket(*args, **kwargs): raise socket.error("Offline mode is enabled")
socket.socket = offline_socket
        '''
       lowercase					:   Tuple				  =self.get_env()
       lowercase					:   Optional[int]				  ='''1'''
       lowercase					:   Union[str, Any]				  =[sys.executable, '''-c''', '''\n'''.join([load, mock, run]		)]
       lowercase					:   Dict				  =subprocess.run(UpperCAmelCase     ,      env=UpperCAmelCase     ,      check=UpperCAmelCase     ,      capture_output=UpperCAmelCase		)
       self.assertEqual(result.returncode     ,      1     ,      result.stderr		)
       self.assertIn(
           '''You cannot infer task automatically within `pipeline` when using offline mode'''     ,      result.stderr.decode().replace('''\n'''     ,      ''''''		)     ,      )






      @require_torch
      def 				A__      ( self			:		int		)  ->  Optional[int]:


       '''simple docstring'''

       lowercase					:   List[str]				  ='''
from transformers import AutoModel
        '''
       lowercase					:   Dict				  ='''
mname = "hf-internal-testing/test_dynamic_model"
AutoModel.from_pretrained(mname, trust_remote_code=True)
print("success")
        '''

       # baseline - just load from_pretrained with normal network
       lowercase					:   Dict				  =[sys.executable, '''-c''', '''\n'''.join([load, run]		)]

       # should succeed
       lowercase					:   Optional[Any]				  =self.get_env()
       lowercase					:   int				  =subprocess.run(UpperCAmelCase     ,      env=UpperCAmelCase     ,      check=UpperCAmelCase     ,      capture_output=UpperCAmelCase		)
       self.assertEqual(result.returncode     ,      0     ,      result.stderr		)
       self.assertIn('''success'''     ,      result.stdout.decode()		)

       # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
       lowercase					:   List[str]				  ='''1'''
       lowercase					:   List[Any]				  =subprocess.run(UpperCAmelCase     ,      env=UpperCAmelCase     ,      check=UpperCAmelCase     ,      capture_output=UpperCAmelCase		)
       self.assertEqual(result.returncode     ,      0     ,      result.stderr		)
       self.assertIn('''success'''     ,      result.stdout.decode()		)



