




'''simple docstring'''


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

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

from transformers import AutoFeatureExtractor, WavaVecaFeatureExtractor
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test


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

from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402


lowerCAmelCase_      :  Tuple				     =  get_tests_dir('fixtures')







class      SCREAMING_SNAKE_CASE    (						unittest.TestCase				):






      def 							lowercase_						( self   :  List[str]       ):


           '''simple docstring'''

           a_     :							Union[str, Any]     						=  mock.Mock()
           a_     :							Union[str, Any]     						=  500
           a_     :							Tuple     						=  {}
           a_     :							int     						=  HTTPError
           a_     :							Tuple     						=  {}

           # Download this model to make sure it's in the cache.
           a_     :							int     						=  WavaVecaFeatureExtractor.from_pretrained("""hf-internal-testing/tiny-random-wav2vec2"""       )
           # Under the mock environment we get a 500 error when trying to reach the model.
           with mock.patch("""requests.Session.request"""						,						return_value=lowercase__       ) as mock_head:
                a_     :							Union[str, Any]     						=  WavaVecaFeatureExtractor.from_pretrained("""hf-internal-testing/tiny-random-wav2vec2"""       )
                # This check we did call the fake head request
                mock_head.assert_called()






      def 							lowercase_						( self   :  Union[str, Any]       ):


           '''simple docstring'''

           a_     :							Union[str, Any]     						=  WavaVecaFeatureExtractor.from_pretrained(
               """https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json"""       )







@is_staging_test
class      SCREAMING_SNAKE_CASE    (						unittest.TestCase				):






      @classmethod
      def 							lowercase_						( cls   :  Dict       ):


           '''simple docstring'''

           a_     :							int     						=  TOKEN
           HfFolder.save_token(lowercase__       )






      @classmethod
      def 							lowercase_						( cls   :  int       ):


           '''simple docstring'''

           try:
                delete_repo(token=cls._token						,						repo_id="""test-feature-extractor"""       )
           except HTTPError:
                pass

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

           try:
                delete_repo(token=cls._token						,						repo_id="""test-dynamic-feature-extractor"""       )
           except HTTPError:
                pass






      def 							lowercase_						( self   :  Tuple       ):


           '''simple docstring'''

           a_     :							Union[str, Any]     						=  WavaVecaFeatureExtractor.from_pretrained(lowercase__       )
           feature_extractor.push_to_hub("""test-feature-extractor"""						,						use_auth_token=self._token       )

           a_     :							Optional[Any]     						=  WavaVecaFeatureExtractor.from_pretrained(F"{USER}/test-feature-extractor"       )
           for k, v in feature_extractor.__dict__.items():
                self.assertEqual(lowercase__						,						getattr(lowercase__						,						lowercase__       )       )

           # Reset repo
           delete_repo(token=self._token						,						repo_id="""test-feature-extractor"""       )

           # Push to hub via save_pretrained
           with tempfile.TemporaryDirectory() as tmp_dir:
                feature_extractor.save_pretrained(
                    lowercase__						,						repo_id="""test-feature-extractor"""						,						push_to_hub=lowercase__						,						use_auth_token=self._token       )

           a_     :							Union[str, Any]     						=  WavaVecaFeatureExtractor.from_pretrained(F"{USER}/test-feature-extractor"       )
           for k, v in feature_extractor.__dict__.items():
                self.assertEqual(lowercase__						,						getattr(lowercase__						,						lowercase__       )       )






      def 							lowercase_						( self   :  Any       ):


           '''simple docstring'''

           a_     :							Optional[Any]     						=  WavaVecaFeatureExtractor.from_pretrained(lowercase__       )
           feature_extractor.push_to_hub("""valid_org/test-feature-extractor"""						,						use_auth_token=self._token       )

           a_     :							Optional[int]     						=  WavaVecaFeatureExtractor.from_pretrained("""valid_org/test-feature-extractor"""       )
           for k, v in feature_extractor.__dict__.items():
                self.assertEqual(lowercase__						,						getattr(lowercase__						,						lowercase__       )       )

           # Reset repo
           delete_repo(token=self._token						,						repo_id="""valid_org/test-feature-extractor"""       )

           # Push to hub via save_pretrained
           with tempfile.TemporaryDirectory() as tmp_dir:
                feature_extractor.save_pretrained(
                    lowercase__						,						repo_id="""valid_org/test-feature-extractor-org"""						,						push_to_hub=lowercase__						,						use_auth_token=self._token       )

           a_     :							Any     						=  WavaVecaFeatureExtractor.from_pretrained("""valid_org/test-feature-extractor-org"""       )
           for k, v in feature_extractor.__dict__.items():
                self.assertEqual(lowercase__						,						getattr(lowercase__						,						lowercase__       )       )






      def 							lowercase_						( self   :  List[str]       ):


           '''simple docstring'''

           CustomFeatureExtractor.register_for_auto_class()
           a_     :							Tuple     						=  CustomFeatureExtractor.from_pretrained(lowercase__       )

           feature_extractor.push_to_hub("""test-dynamic-feature-extractor"""						,						use_auth_token=self._token       )

           # This has added the proper auto_map field to the config
           self.assertDictEqual(
               feature_extractor.auto_map						,						{"""AutoFeatureExtractor""": """custom_feature_extraction.CustomFeatureExtractor"""}						,						)

           a_     :							int     						=  AutoFeatureExtractor.from_pretrained(
               F"{USER}/test-dynamic-feature-extractor"						,						trust_remote_code=lowercase__       )
           # Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module
           self.assertEqual(new_feature_extractor.__class__.__name__						,						"""CustomFeatureExtractor"""       )






'''simple docstring'''


from math import sqrt

import numpy as np
from sympy import symbols

# Coefficient
# Speed of light (m/s)
lowerCAmelCase_      :  List[Any]				     =  2_9979_2458

# Symbols
lowerCAmelCase_     ,   lowerCAmelCase_     ,   lowerCAmelCase_     ,   lowerCAmelCase_      :  Tuple				     =  symbols('ct x y z')



def  _SCREAMING_SNAKE_CASE     (      UpperCamelCase__    :					float				):




     """simple docstring"""


     if velocity > c:
          raise ValueError("""Speed must not exceed light speed 299,792,458 [m/s]!"""				)
     elif velocity < 1:
          # Usually the speed should be much higher than 1 (c order of magnitude)
          raise ValueError("""Speed must be greater than or equal to 1!"""				)

     return velocity / c



def  _SCREAMING_SNAKE_CASE     (      UpperCamelCase__    :					float				):




     """simple docstring"""


     return 1 / sqrt(1 - beta(UpperCamelCase__				) ** 2				)



def  _SCREAMING_SNAKE_CASE     (      UpperCamelCase__    :					float				):




     """simple docstring"""


     return np.array(
         [
             [gamma(UpperCamelCase__				), -gamma(UpperCamelCase__				) * beta(UpperCamelCase__				), 0, 0],
             [-gamma(UpperCamelCase__				) * beta(UpperCamelCase__				), gamma(UpperCamelCase__				), 0, 0],
             [0, 0, 1, 0],
             [0, 0, 0, 1],
         ]				)



def  _SCREAMING_SNAKE_CASE     (      UpperCamelCase__    :					float ,    UpperCamelCase__    :					np.ndarray | None = None				):




     """simple docstring"""


     if event is None:
          a_     :							str     						=  np.array([ct, x, y, z]				)  # Symbolic four vector
     else:
          event[0] *= c  # x0 is ct (speed of light * time)

     return transformation_matrix(UpperCamelCase__				) @ event


if __name__ == "__main__":
 import doctest

 doctest.testmod()

 # Example of symbolic vector:
 lowerCAmelCase_      :  Union[str, Any]				     =  transform(2997_9245)
 print('Example of four vector: ')
 print(f"ct' = {four_vector[0]}")
 print(f"x' = {four_vector[1]}")
 print(f"y' = {four_vector[2]}")
 print(f"z' = {four_vector[3]}")

 # Substitute symbols with numerical values
 lowerCAmelCase_      :  Tuple				     =  {ct: c, x: 1, y: 1, z: 1}
 lowerCAmelCase_      :  Optional[int]				     =  [four_vector[i].subs(sub_dict) for i in range(4)]

 print(f"\n{numerical_vector}")
