

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


snake_case_         =					get_tests_dir('''fixtures''')


class  SCREAMING_SNAKE_CASE__   (unittest.TestCase	):





    def  snake_case_							( self):
         lowercase__       :  int =			mock.Mock()
         lowercase__       :  int =			500
         lowercase__       :  Any =			{}
         lowercase__       :  Union[str, Any] =			HTTPError
         lowercase__       :  Dict =			{}

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





    def  snake_case_							( self):
         lowercase__       :  Optional[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  snake_case_							( cls):
         lowercase__       :  str =			TOKEN
         HfFolder.save_token(__UpperCamelCase)





    @classmethod
    def  snake_case_							( cls):






         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  snake_case_							( self):
         lowercase__       :  Optional[Any] =			WavaVecaFeatureExtractor.from_pretrained(__UpperCamelCase)
         feature_extractor.push_to_hub('test-feature-extractor'		,  use_auth_token=self._token)

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

         # 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(
                  __UpperCamelCase		,  repo_id='test-feature-extractor'		,  push_to_hub=__UpperCamelCase		,  use_auth_token=self._token)

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





    def  snake_case_							( self):
         lowercase__       :  Dict =			WavaVecaFeatureExtractor.from_pretrained(__UpperCamelCase)
         feature_extractor.push_to_hub('valid_org/test-feature-extractor'		,  use_auth_token=self._token)

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

         # 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(
                  __UpperCamelCase		,  repo_id='valid_org/test-feature-extractor-org'		,  push_to_hub=__UpperCamelCase		,  use_auth_token=self._token)

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





    def  snake_case_							( self):
         CustomFeatureExtractor.register_for_auto_class()
         lowercase__       :  Optional[int] =			CustomFeatureExtractor.from_pretrained(__UpperCamelCase)

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

         lowercase__       :  str =			AutoFeatureExtractor.from_pretrained(
             f"""{USER}/test-dynamic-feature-extractor"""		,  trust_remote_code=__UpperCamelCase)
         # 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 unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch


if is_torch_available():
 import torch

 from transformers.generation import DisjunctiveConstraint




@require_torch
class 		a_    (			unittest.TestCase						):







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






        '''simple docstring'''






        _UpperCAmelCase        = [[1, 2, 4], [1, 2, 3, 4]]
        _UpperCAmelCase        = DisjunctiveConstraint(__UpperCamelCase  )
        self.assertTrue(isinstance(dc.token_ids  ,       __UpperCamelCase  )  )

        with self.assertRaises(__UpperCamelCase  ):
            DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]]  )  )

        with self.assertRaises(__UpperCamelCase  ):
            DisjunctiveConstraint([torch.LongTensor([1, 2, 4]  ), torch.LongTensor([1, 2, 3, 4, 5]  )]  )







    def   _snake_case       (      self      :							Optional[int]  )		->Dict:






        '''simple docstring'''






        _UpperCAmelCase        = [[1, 2], [1, 2, 3, 4]]

        with self.assertRaises(__UpperCamelCase  ):
            DisjunctiveConstraint(__UpperCamelCase  )  # fails here







    def   _snake_case       (      self      :							Optional[int]  )		->Dict:






        '''simple docstring'''






        _UpperCAmelCase        = [[1, 2, 3], [1, 2, 4]]

        _UpperCAmelCase        = DisjunctiveConstraint(__UpperCamelCase  )

        _UpperCAmelCase     ,_UpperCAmelCase     ,_UpperCAmelCase        = dc.update(1  )
        _UpperCAmelCase        = stepped is True and completed is False and reset is False
        self.assertTrue(__UpperCamelCase  )
        self.assertTrue(not dc.completed  )
        self.assertTrue(dc.current_seq == [1]  )

        _UpperCAmelCase     ,_UpperCAmelCase     ,_UpperCAmelCase        = dc.update(2  )
        _UpperCAmelCase        = stepped is True and completed is False and reset is False
        self.assertTrue(__UpperCamelCase  )
        self.assertTrue(not dc.completed  )
        self.assertTrue(dc.current_seq == [1, 2]  )

        _UpperCAmelCase     ,_UpperCAmelCase     ,_UpperCAmelCase        = dc.update(3  )
        _UpperCAmelCase        = stepped is True and completed is True and reset is False
        self.assertTrue(__UpperCamelCase  )
        self.assertTrue(dc.completed  )  # Completed!
        self.assertTrue(dc.current_seq == [1, 2, 3]  )







    def   _snake_case       (      self      :							List[Any]  )		->Any:






        '''simple docstring'''






        _UpperCAmelCase        = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]]

        _UpperCAmelCase        = DisjunctiveConstraint(__UpperCamelCase  )

        _UpperCAmelCase     ,_UpperCAmelCase     ,_UpperCAmelCase        = dc.update(1  )
        self.assertTrue(not dc.completed  )
        self.assertTrue(dc.current_seq == [1]  )

        _UpperCAmelCase     ,_UpperCAmelCase     ,_UpperCAmelCase        = dc.update(2  )
        self.assertTrue(not dc.completed  )
        self.assertTrue(dc.current_seq == [1, 2]  )

        _UpperCAmelCase     ,_UpperCAmelCase     ,_UpperCAmelCase        = dc.update(4  )
        self.assertTrue(not dc.completed  )
        self.assertTrue(dc.current_seq == [1, 2, 4]  )

        _UpperCAmelCase     ,_UpperCAmelCase     ,_UpperCAmelCase        = dc.update(5  )
        self.assertTrue(dc.completed  )  # Completed!
        self.assertTrue(dc.current_seq == [1, 2, 4, 5]  )

        dc.reset()

        _UpperCAmelCase     ,_UpperCAmelCase     ,_UpperCAmelCase        = dc.update(1  )
        self.assertTrue(not dc.completed  )
        self.assertTrue(dc.remaining() == 3  )
        self.assertTrue(dc.current_seq == [1]  )

        _UpperCAmelCase     ,_UpperCAmelCase     ,_UpperCAmelCase        = dc.update(2  )
        self.assertTrue(not dc.completed  )
        self.assertTrue(dc.remaining() == 2  )
        self.assertTrue(dc.current_seq == [1, 2]  )

        _UpperCAmelCase     ,_UpperCAmelCase     ,_UpperCAmelCase        = dc.update(5  )
        self.assertTrue(dc.completed  )  # Completed!
        self.assertTrue(dc.remaining() == 0  )
        self.assertTrue(dc.current_seq == [1, 2, 5]  )