





'''simple docstring'''

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,
)


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





class lowerCamelCase						(unittest.TestCase					):







  def 				UpperCAmelCase_				(		self		)		->						Dict:






        """simple docstring"""





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

        # File is cached at the same place the second time.
        _snake_case		:	Optional[int]					     =     cached_file(lowercase__     ,     lowercase__		)
        self.assertEqual(lowercase__     ,     lowercase__		)

        # Using a specific revision to test the full commit hash.
        _snake_case		:	List[str]					     =     cached_file(lowercase__     ,     lowercase__     ,     revision='''9b8c223'''		)
        self.assertEqual(lowercase__     ,     os.path.join(lowercase__     ,     '''snapshots'''     ,     lowercase__     ,     lowercase__		)		)







  def 				UpperCAmelCase_				(		self		)		->						Union[str, Any]:






        """simple docstring"""





        with self.assertRaisesRegex(lowercase__     ,     '''is not a valid model identifier'''		):
              _snake_case		:	Any					     =     cached_file('''tiny-random-bert'''     ,     lowercase__		)

        with self.assertRaisesRegex(lowercase__     ,     '''is not a valid git identifier'''		):
              _snake_case		:	Tuple					     =     cached_file(lowercase__     ,     lowercase__     ,     revision='''aaaa'''		)

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







  def 				UpperCAmelCase_				(		self		)		->						Union[str, Any]:






        """simple docstring"""





        with self.assertRaisesRegex(lowercase__     ,     '''does not appear to have a file named'''		):
              _snake_case		:	List[Any]					     =     cached_file(lowercase__     ,     '''conf'''		)

        with open(os.path.join(lowercase__     ,     '''refs'''     ,     '''main'''		)		) as f:
              _snake_case		:	Optional[Any]					     =     f.read()
        self.assertTrue(os.path.isfile(os.path.join(lowercase__     ,     '''.no_exist'''     ,     lowercase__     ,     '''conf'''		)		)		)

        _snake_case		:	Any					     =     cached_file(lowercase__     ,     '''conf'''     ,     _raise_exceptions_for_missing_entries=lowercase__		)
        self.assertIsNone(lowercase__		)

        _snake_case		:	Union[str, Any]					     =     cached_file(lowercase__     ,     '''conf'''     ,     local_files_only=lowercase__     ,     _raise_exceptions_for_missing_entries=lowercase__		)
        self.assertIsNone(lowercase__		)

        _snake_case		:	List[Any]					     =     mock.Mock()
        _snake_case		:	Union[str, Any]					     =     500
        _snake_case		:	Any					     =     {}
        _snake_case		:	Dict					     =     HTTPError
        _snake_case		:	Tuple					     =     {}

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







  def 				UpperCAmelCase_				(		self		)		->						Optional[Any]:






        """simple docstring"""





        self.assertTrue(has_file('''hf-internal-testing/tiny-bert-pt-only'''     ,     lowercase__		)		)
        self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only'''     ,     lowercase__		)		)
        self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only'''     ,     lowercase__		)		)







  def 				UpperCAmelCase_				(		self		)		->						str:






        """simple docstring"""





        self.assertIsNone(get_file_from_repo('''bert-base-cased'''     ,     '''ahah.txt'''		)		)

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

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

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







  def 				UpperCAmelCase_				(		self		)		->						List[str]:






        """simple docstring"""





        with tempfile.TemporaryDirectory() as tmp_dir:
              _snake_case		:	Dict					     =     Path(lowercase__		) / '''a.txt'''
              filename.touch()
              self.assertEqual(get_file_from_repo(lowercase__     ,     '''a.txt'''		)     ,     str(lowercase__		)		)

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









'''simple docstring'''

import functools
import operator

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


UpperCAmelCase					:		List[str]		=							logging.get_logger(__name__)

UpperCAmelCase					:		Dict		=							{
    'asapp/sew-d-tiny-100k': 'https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json',
    # See all SEW-D models at https://huggingface.co/models?filter=sew-d
}





class lowerCamelCase						(a__					):
  _lowercase  :	List[str]       					=				"""sew-d"""







  def __init__(		self     ,     lowercase__=32     ,     lowercase__=768     ,     lowercase__=12     ,     lowercase__=12     ,     lowercase__=3_072     ,     lowercase__=2     ,     lowercase__=512     ,     lowercase__=256     ,     lowercase__=True     ,     lowercase__=True     ,     lowercase__=("p2c", "c2p")     ,     lowercase__="layer_norm"     ,     lowercase__="gelu_python"     ,     lowercase__=0.1     ,     lowercase__=0.1     ,     lowercase__=0.1     ,     lowercase__=0.0     ,     lowercase__=0.1     ,     lowercase__=0.02     ,     lowercase__=1E-7     ,     lowercase__=1E-5     ,     lowercase__="group"     ,     lowercase__="gelu"     ,     lowercase__=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512)     ,     lowercase__=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1)     ,     lowercase__=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1)     ,     lowercase__=False     ,     lowercase__=128     ,     lowercase__=16     ,     lowercase__=True     ,     lowercase__=0.05     ,     lowercase__=10     ,     lowercase__=2     ,     lowercase__=0.0     ,     lowercase__=10     ,     lowercase__=0     ,     lowercase__="mean"     ,     lowercase__=False     ,     lowercase__=False     ,     lowercase__=256     ,     lowercase__=0     ,     lowercase__=1     ,     lowercase__=2     ,     **lowercase__     ,     )		->						Dict:






        """simple docstring"""





        super().__init__(**lowercase__     ,     pad_token_id=lowercase__     ,     bos_token_id=lowercase__     ,     eos_token_id=lowercase__		)
        _snake_case		:	List[str]					     =     hidden_size
        _snake_case		:	Optional[Any]					     =     feat_extract_norm
        _snake_case		:	Tuple					     =     feat_extract_activation
        _snake_case		:	Tuple					     =     list(lowercase__		)
        _snake_case		:	Any					     =     list(lowercase__		)
        _snake_case		:	Any					     =     list(lowercase__		)
        _snake_case		:	Any					     =     conv_bias
        _snake_case		:	List[Any]					     =     num_conv_pos_embeddings
        _snake_case		:	Any					     =     num_conv_pos_embedding_groups
        _snake_case		:	Union[str, Any]					     =     len(self.conv_dim		)
        _snake_case		:	Optional[Any]					     =     num_hidden_layers
        _snake_case		:	Optional[int]					     =     intermediate_size
        _snake_case		:	Any					     =     squeeze_factor
        _snake_case		:	Optional[Any]					     =     max_position_embeddings
        _snake_case		:	Tuple					     =     position_buckets
        _snake_case		:	Tuple					     =     share_att_key
        _snake_case		:	Any					     =     relative_attention
        _snake_case		:	Optional[int]					     =     norm_rel_ebd
        _snake_case		:	Optional[Any]					     =     list(lowercase__		)
        _snake_case		:	List[Any]					     =     hidden_act
        _snake_case		:	List[Any]					     =     num_attention_heads
        _snake_case		:	Dict					     =     hidden_dropout
        _snake_case		:	Tuple					     =     attention_dropout
        _snake_case		:	Union[str, Any]					     =     activation_dropout
        _snake_case		:	List[Any]					     =     feat_proj_dropout
        _snake_case		:	Optional[int]					     =     final_dropout
        _snake_case		:	Optional[Any]					     =     layer_norm_eps
        _snake_case		:	Dict					     =     feature_layer_norm_eps
        _snake_case		:	List[Any]					     =     initializer_range
        _snake_case		:	Dict					     =     vocab_size

        if (
            (len(self.conv_stride		) != self.num_feat_extract_layers)
            or (len(self.conv_kernel		) != self.num_feat_extract_layers)
            or (len(self.conv_dim		) != self.num_feat_extract_layers)
        ):
              raise ValueError(
                  '''Configuration for convolutional layers is incorrect.'''
                  '''It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,'''
                  F'''but is `len(config.conv_dim) = {len(self.conv_dim		)}`, `len(config.conv_stride)'''
                  F'''= {len(self.conv_stride		)}`, `len(config.conv_kernel) = {len(self.conv_kernel		)}`.'''		)

        # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
        _snake_case		:	Union[str, Any]					     =     apply_spec_augment
        _snake_case		:	Any					     =     mask_time_prob
        _snake_case		:	List[str]					     =     mask_time_length
        _snake_case		:	Dict					     =     mask_time_min_masks
        _snake_case		:	Union[str, Any]					     =     mask_feature_prob
        _snake_case		:	Tuple					     =     mask_feature_length
        _snake_case		:	Union[str, Any]					     =     mask_feature_min_masks

        # ctc loss
        _snake_case		:	Optional[Any]					     =     ctc_loss_reduction
        _snake_case		:	Optional[Any]					     =     ctc_zero_infinity

        # sequence classification
        _snake_case		:	List[Any]					     =     use_weighted_layer_sum
        _snake_case		:	Any					     =     classifier_proj_size







  @property
  def 				UpperCAmelCase_				(		self		)		->						Any:






        """simple docstring"""





        return functools.reduce(operator.mul     ,     self.conv_stride     ,     1		)


