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


__magic_name__    		=get_tests_dir('''fixtures''')



class      _A (     unittest.TestCase				):






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





       '''simple docstring'''





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

       # Download this model to make sure it's in the cache.
       UpperCamelCase__					    =   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:
            UpperCamelCase__					    =   WavaVecaFeatureExtractor.from_pretrained('''hf-internal-testing/tiny-random-wav2vec2'''						)
            # This check we did call the fake head request
            mock_head.assert_called()






  def 		_a       (self						)		->   int:





       '''simple docstring'''





       UpperCamelCase__					    =   WavaVecaFeatureExtractor.from_pretrained(
           '''https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json'''						)



@is_staging_test
class      _A (     unittest.TestCase				):






  @classmethod
  def 		_a       (cls						)		->   int:





       '''simple docstring'''





       UpperCamelCase__					    =   TOKEN
       HfFolder.save_token(_lowercase						)






  @classmethod
  def 		_a       (cls						)		->   str:





       '''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 		_a       (self						)		->   Optional[int]:





       '''simple docstring'''





       UpperCamelCase__					    =   WavaVecaFeatureExtractor.from_pretrained(_lowercase						)
       feature_extractor.push_to_hub('''test-feature-extractor''' ,					use_auth_token=self._token						)

       UpperCamelCase__					    =   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						)

       UpperCamelCase__					    =   WavaVecaFeatureExtractor.from_pretrained(F"{USER}/test-feature-extractor"						)
       for k, v in feature_extractor.__dict__.items():
            self.assertEqual(_lowercase ,					getattr(_lowercase ,					_lowercase						)						)






  def 		_a       (self						)		->   int:





       '''simple docstring'''





       UpperCamelCase__					    =   WavaVecaFeatureExtractor.from_pretrained(_lowercase						)
       feature_extractor.push_to_hub('''valid_org/test-feature-extractor''' ,					use_auth_token=self._token						)

       UpperCamelCase__					    =   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						)

       UpperCamelCase__					    =   WavaVecaFeatureExtractor.from_pretrained('''valid_org/test-feature-extractor-org'''						)
       for k, v in feature_extractor.__dict__.items():
            self.assertEqual(_lowercase ,					getattr(_lowercase ,					_lowercase						)						)






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





       '''simple docstring'''





       CustomFeatureExtractor.register_for_auto_class()
       UpperCamelCase__					    =   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'''} ,					)

       UpperCamelCase__					    =   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'''
import math
from typing import List, Optional, Tuple, Union

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from .scheduling_utils import SchedulerMixin, SchedulerOutput
class   __UpperCAmelCase				(     lowerCAmelCase			,lowerCAmelCase				):



					'''simple docstring'''





					_UpperCamelCase							=		1



					@register_to_config
					def __init__(	self     :						str      ,       _lowercase     :						int = 1_000      ,       _lowercase     :						Optional[Union[np.ndarray, List[float]]] = None)    ->							List[str]:
								# set `betas`, `alphas`, `timesteps`
								self.set_timesteps(_lowercase)

								# standard deviation of the initial noise distribution
								A_									= 1.0

								# For now we only support F-PNDM, i.e. the runge-kutta method
								# For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf
								# mainly at formula (9), (12), (13) and the Algorithm 2.
								A_									= 4

								# running values
								A_									= []



					def     __snake_case						(	self     :						int      ,       _lowercase     :						int      ,       _lowercase     :						Union[str, torch.device] = None)    ->							Any:
								A_									= num_inference_steps
								A_									= torch.linspace(1      ,       0      ,       num_inference_steps + 1)[:-1]
								A_									= torch.cat([steps, torch.tensor([0.0])])

								if self.config.trained_betas is not None:
											A_									= torch.tensor(self.config.trained_betas      ,       dtype=torch.floataa)
								else:
											A_									= torch.sin(steps * math.pi / 2) ** 2

								A_									= (1.0 - self.betas**2) ** 0.5

								A_									= (torch.atana(self.betas      ,       self.alphas) / math.pi * 2)[:-1]
								A_									= timesteps.to(_lowercase)

								A_									= []



					def     __snake_case						(	self     :						Dict      ,       _lowercase     :						torch.FloatTensor      ,       _lowercase     :						int      ,       _lowercase     :						torch.FloatTensor      ,       _lowercase     :						bool = True      ,       )    ->							Union[SchedulerOutput, Tuple]:
								if self.num_inference_steps is None:
											raise ValueError(
											    'Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler')

								A_									= (self.timesteps == timestep).nonzero().item()
								A_									= timestep_index + 1

								A_									= sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index]
								self.ets.append(_lowercase)

								if len(self.ets) == 1:
											A_									= self.ets[-1]
								elif len(self.ets) == 2:
											A_									= (3 * self.ets[-1] - self.ets[-2]) / 2
								elif len(self.ets) == 3:
											A_									= (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12
								else:
											A_									= (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4])

								A_									= self._get_prev_sample(_lowercase      ,       _lowercase      ,       _lowercase      ,       _lowercase)

								if not return_dict:
											return (prev_sample,)

								return SchedulerOutput(prev_sample=_lowercase)



					def     __snake_case						(	self     :						Dict      ,       _lowercase     :						torch.FloatTensor      ,       *_lowercase     :						Optional[Any]      ,       **_lowercase     :						int)    ->							torch.FloatTensor:
								return sample



					def     __snake_case						(	self     :						Optional[int]      ,       _lowercase     :						Optional[Any]      ,       _lowercase     :						Dict      ,       _lowercase     :						Union[str, Any]      ,       _lowercase     :						Union[str, Any])    ->							Union[str, Any]:
								A_									= self.alphas[timestep_index]
								A_									= self.betas[timestep_index]

								A_									= self.alphas[prev_timestep_index]
								A_									= self.betas[prev_timestep_index]

								A_									= (sample - sigma * ets) / max(_lowercase      ,       1E-8)
								A_									= next_alpha * pred + ets * next_sigma

								return prev_sample



					def __len__(	self     :						List[str])    ->							Union[str, Any]:
								return self.config.num_train_timesteps




