





import unittest

import numpy as np

from transformers import RobertaConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask


if is_flax_available():
       from transformers.models.roberta.modeling_flax_roberta import (
           FlaxRobertaForCausalLM,
           FlaxRobertaForMaskedLM,
           FlaxRobertaForMultipleChoice,
           FlaxRobertaForQuestionAnswering,
           FlaxRobertaForSequenceClassification,
           FlaxRobertaForTokenClassification,
           FlaxRobertaModel,
       )




class        SCREAMING_SNAKE_CASE__					(		unittest.TestCase ):



 def __init__(				self,__lowerCamelCase,__lowerCamelCase=13,__lowerCamelCase=7,__lowerCamelCase=True,__lowerCamelCase=True,__lowerCamelCase=True,__lowerCamelCase=True,__lowerCamelCase=99,__lowerCamelCase=32,__lowerCamelCase=5,__lowerCamelCase=4,__lowerCamelCase=37,__lowerCamelCase="gelu",__lowerCamelCase=0.1,__lowerCamelCase=0.1,__lowerCamelCase=512,__lowerCamelCase=16,__lowerCamelCase=2,__lowerCamelCase=0.02,__lowerCamelCase=4,):
        A__		   =		parent
        A__		   =		batch_size
        A__		   =		seq_length
        A__		   =		is_training
        A__		   =		use_attention_mask
        A__		   =		use_token_type_ids
        A__		   =		use_labels
        A__		   =		vocab_size
        A__		   =		hidden_size
        A__		   =		num_hidden_layers
        A__		   =		num_attention_heads
        A__		   =		intermediate_size
        A__		   =		hidden_act
        A__		   =		hidden_dropout_prob
        A__		   =		attention_probs_dropout_prob
        A__		   =		max_position_embeddings
        A__		   =		type_vocab_size
        A__		   =		type_sequence_label_size
        A__		   =		initializer_range
        A__		   =		num_choices



 def 							UpperCamelCase     (				self					):
        A__		   =		ids_tensor([self.batch_size, self.seq_length],self.vocab_size					)

        A__		   =		None
        if self.use_attention_mask:
               A__		   =		random_attention_mask([self.batch_size, self.seq_length]					)

        A__		   =		None
        if self.use_token_type_ids:
               A__		   =		ids_tensor([self.batch_size, self.seq_length],self.type_vocab_size					)

        A__		   =		RobertaConfig(
            vocab_size=self.vocab_size,hidden_size=self.hidden_size,num_hidden_layers=self.num_hidden_layers,num_attention_heads=self.num_attention_heads,intermediate_size=self.intermediate_size,hidden_act=self.hidden_act,hidden_dropout_prob=self.hidden_dropout_prob,attention_probs_dropout_prob=self.attention_probs_dropout_prob,max_position_embeddings=self.max_position_embeddings,type_vocab_size=self.type_vocab_size,is_decoder=__lowerCamelCase,initializer_range=self.initializer_range,)

        return config, input_ids, token_type_ids, attention_mask



 def 							UpperCamelCase     (				self					):
        A__		   =		self.prepare_config_and_inputs()
        A__   ,      A__   ,      A__   ,      A__		   =		config_and_inputs
        A__		   =		{'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask}
        return config, inputs_dict




 def 							UpperCamelCase     (				self					):
        A__		   =		self.prepare_config_and_inputs()
        A__   ,      A__   ,      A__   ,      A__		   =		config_and_inputs

        A__		   =		True
        A__		   =		floats_tensor([self.batch_size, self.seq_length, self.hidden_size]					)
        A__		   =		ids_tensor([self.batch_size, self.seq_length],vocab_size=2					)

        return (
            config,
            input_ids,
            token_type_ids,
            encoder_hidden_states,
            encoder_attention_mask,
        )




@require_flax
class        SCREAMING_SNAKE_CASE__					(		UpperCamelCase__							,   unittest.TestCase ):
 __SCREAMING_SNAKE_CASE							=      True

 __SCREAMING_SNAKE_CASE							=      (
     (
         FlaxRobertaModel,
         FlaxRobertaForCausalLM,
         FlaxRobertaForMaskedLM,
         FlaxRobertaForSequenceClassification,
         FlaxRobertaForTokenClassification,
         FlaxRobertaForMultipleChoice,
         FlaxRobertaForQuestionAnswering,
     )
     if is_flax_available()
     else ()
 )



 def 							UpperCamelCase     (				self					):
        A__		   =		FlaxRobertaModelTester(self					)




 @slow
 def 							UpperCamelCase     (				self					):
        for model_class_name in self.all_model_classes:
               A__		   =		model_class_name.from_pretrained('''roberta-base''',from_pt=__lowerCamelCase					)
               A__		   =		model(np.ones((1, 1)					)					)
               self.assertIsNotNone(__lowerCamelCase					)












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

from requests.exceptions import HTTPError

from transformers.utils import (
    CONFIG_NAME,
    FLAX_WEIGHTS_NAME,
    TF2_WEIGHTS_NAME,
    TRANSFORMERS_CACHE,
    WEIGHTS_NAME,
    cached_file,
    get_file_from_repo,
    has_file,
)


a__: Union[str, Any]							   =						'hf-internal-testing/tiny-random-bert'
a__: Optional[int]							   =						os.path.join(TRANSFORMERS_CACHE, 'models--hf-internal-testing--tiny-random-bert')
a__: List[str]							   =						'9b8c223d42b2188cb49d29af482996f9d0f3e5a6'




class        SCREAMING_SNAKE_CASE__					(		unittest.TestCase ):



 def 							UpperCamelCase     (				self					):
        A__		   =		cached_file(__lowerCamelCase,__lowerCamelCase					)
        # Should have downloaded the file in here
        self.assertTrue(os.path.isdir(__lowerCamelCase					)					)
        # Cache should contain at least those three subfolders:
        for subfolder in ["blobs", "refs", "snapshots"]:
               self.assertTrue(os.path.isdir(os.path.join(__lowerCamelCase,__lowerCamelCase					)					)					)
        with open(os.path.join(__lowerCamelCase,'''refs''','''main'''					)					) as f:
               A__		   =		f.read()
        self.assertEqual(__lowerCamelCase,os.path.join(__lowerCamelCase,'''snapshots''',__lowerCamelCase,__lowerCamelCase					)					)
        self.assertTrue(os.path.isfile(__lowerCamelCase					)					)

        # File is cached at the same place the second time.
        A__		   =		cached_file(__lowerCamelCase,__lowerCamelCase					)
        self.assertEqual(__lowerCamelCase,__lowerCamelCase					)

        # Using a specific revision to test the full commit hash.
        A__		   =		cached_file(__lowerCamelCase,__lowerCamelCase,revision='''9b8c223'''					)
        self.assertEqual(__lowerCamelCase,os.path.join(__lowerCamelCase,'''snapshots''',__lowerCamelCase,__lowerCamelCase					)					)



 def 							UpperCamelCase     (				self					):
        with self.assertRaisesRegex(__lowerCamelCase,'''is not a valid model identifier'''					):
               A__		   =		cached_file('''tiny-random-bert''',__lowerCamelCase					)

        with self.assertRaisesRegex(__lowerCamelCase,'''is not a valid git identifier'''					):
               A__		   =		cached_file(__lowerCamelCase,__lowerCamelCase,revision='''aaaa'''					)

        with self.assertRaisesRegex(__lowerCamelCase,'''does not appear to have a file named'''					):
               A__		   =		cached_file(__lowerCamelCase,'''conf'''					)



 def 							UpperCamelCase     (				self					):
        with self.assertRaisesRegex(__lowerCamelCase,'''does not appear to have a file named'''					):
               A__		   =		cached_file(__lowerCamelCase,'''conf'''					)

        with open(os.path.join(__lowerCamelCase,'''refs''','''main'''					)					) as f:
               A__		   =		f.read()
        self.assertTrue(os.path.isfile(os.path.join(__lowerCamelCase,'''.no_exist''',__lowerCamelCase,'''conf'''					)					)					)

        A__		   =		cached_file(__lowerCamelCase,'''conf''',_raise_exceptions_for_missing_entries=__lowerCamelCase					)
        self.assertIsNone(__lowerCamelCase					)

        A__		   =		cached_file(__lowerCamelCase,'''conf''',local_files_only=__lowerCamelCase,_raise_exceptions_for_missing_entries=__lowerCamelCase					)
        self.assertIsNone(__lowerCamelCase					)

        A__		   =		mock.Mock()
        A__		   =		500
        A__		   =		{}
        A__		   =		HTTPError
        A__		   =		{}

        # Under the mock environment we get a 500 error when trying to reach the tokenizer.
        with mock.patch('''requests.Session.request''',return_value=__lowerCamelCase					) as mock_head:
               A__		   =		cached_file(__lowerCamelCase,'''conf''',_raise_exceptions_for_connection_errors=__lowerCamelCase					)
               self.assertIsNone(__lowerCamelCase					)
               # This check we did call the fake head request
               mock_head.assert_called()



 def 							UpperCamelCase     (				self					):
        self.assertTrue(has_file('''hf-internal-testing/tiny-bert-pt-only''',__lowerCamelCase					)					)
        self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only''',__lowerCamelCase					)					)
        self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only''',__lowerCamelCase					)					)



 def 							UpperCamelCase     (				self					):
        # `get_file_from_repo` returns None if the file does not exist
        self.assertIsNone(get_file_from_repo('''bert-base-cased''','''ahah.txt'''					)					)

        # The function raises if the repository does not exist.
        with self.assertRaisesRegex(__lowerCamelCase,'''is not a valid model identifier'''					):
               get_file_from_repo('''bert-base-case''',__lowerCamelCase					)

        # The function raises if the revision does not exist.
        with self.assertRaisesRegex(__lowerCamelCase,'''is not a valid git identifier'''					):
               get_file_from_repo('''bert-base-cased''',__lowerCamelCase,revision='''ahaha'''					)

        A__		   =		get_file_from_repo('''bert-base-cased''',__lowerCamelCase					)
        # The name is the cached name which is not very easy to test, so instead we load the content.
        A__		   =		json.loads(open(__lowerCamelCase,'''r'''					).read()					)
        self.assertEqual(config['''hidden_size'''],768					)




 def 							UpperCamelCase     (				self					):
        with tempfile.TemporaryDirectory() as tmp_dir:
               A__		   =		Path(__lowerCamelCase					) / '''a.txt'''
               filename.touch()
               self.assertEqual(get_file_from_repo(__lowerCamelCase,'''a.txt'''					),str(__lowerCamelCase					)					)

               self.assertIsNone(get_file_from_repo(__lowerCamelCase,'''b.txt'''					)					)





