

'''simple docstring'''

import unittest

from transformers import is_vision_available
from transformers.pipelines import pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
       from PIL import Image
else:


       class 	lowerCAmelCase  :







              @staticmethod
              def       snake_case (				*__lowercase      :			str    ,   **__lowercase      :			Dict   ):







                   """simple docstring"""







                   pass


@is_pipeline_test
@require_vision
class 	lowerCAmelCase  (   unittest.TestCase ):







       @require_torch
       def       snake_case (				self      :			List[Any]   ):







            """simple docstring"""







            __lowercase      		=pipeline(
                model='hf-internal-testing/tiny-random-clip-zero-shot-image-classification'    ,   )
            __lowercase      		=Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'   )
            __lowercase      		=image_classifier(__lowercase    ,   candidate_labels=['a', 'b', 'c']   )

            # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across
            # python and torch versions.
            self.assertIn(
                nested_simplify(__lowercase   )    ,   [
                    [{'score': 0.3_3_3, 'label': 'a'}, {'score': 0.3_3_3, 'label': 'b'}, {'score': 0.3_3_3, 'label': 'c'}],
                    [{'score': 0.3_3_3, 'label': 'a'}, {'score': 0.3_3_3, 'label': 'c'}, {'score': 0.3_3_3, 'label': 'b'}],
                ]    ,   )

            __lowercase      		=image_classifier([image] * 5    ,   candidate_labels=['A', 'B', 'C']    ,   batch_size=2   )
            self.assertEqual(
                nested_simplify(__lowercase   )    ,   [
                    [
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                    ],
                    [
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                    ],
                    [
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                    ],
                    [
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                    ],
                    [
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                    ],
                ]    ,   )







       @require_tf
       def       snake_case (				self      :			List[str]   ):







            """simple docstring"""







            __lowercase      		=pipeline(
                model='hf-internal-testing/tiny-random-clip-zero-shot-image-classification'    ,   framework='tf'   )
            __lowercase      		=Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'   )
            __lowercase      		=image_classifier(__lowercase    ,   candidate_labels=['a', 'b', 'c']   )

            self.assertEqual(
                nested_simplify(__lowercase   )    ,   [{'score': 0.3_3_3, 'label': 'a'}, {'score': 0.3_3_3, 'label': 'b'}, {'score': 0.3_3_3, 'label': 'c'}]    ,   )

            __lowercase      		=image_classifier([image] * 5    ,   candidate_labels=['A', 'B', 'C']    ,   batch_size=2   )
            self.assertEqual(
                nested_simplify(__lowercase   )    ,   [
                    [
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                    ],
                    [
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                    ],
                    [
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                    ],
                    [
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                    ],
                    [
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                        {'score': 0.3_3_3, 'label': ANY(__lowercase   )},
                    ],
                ]    ,   )







       @slow
       @require_torch
       def       snake_case (				self      :			Optional[int]   ):







            """simple docstring"""







            __lowercase      		=pipeline(
                task='zero-shot-image-classification'    ,   model='openai/clip-vit-base-patch32'    ,   )
            # This is an image of 2 cats with remotes and no planes
            __lowercase      		=Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'   )
            __lowercase      		=image_classifier(__lowercase    ,   candidate_labels=['cat', 'plane', 'remote']   )

            self.assertEqual(
                nested_simplify(__lowercase   )    ,   [
                    {'score': 0.5_1_1, 'label': 'remote'},
                    {'score': 0.4_8_5, 'label': 'cat'},
                    {'score': 0.0_0_4, 'label': 'plane'},
                ]    ,   )

            __lowercase      		=image_classifier([image] * 5    ,   candidate_labels=['cat', 'plane', 'remote']    ,   batch_size=2   )
            self.assertEqual(
                nested_simplify(__lowercase   )    ,   [
                    [
                        {'score': 0.5_1_1, 'label': 'remote'},
                        {'score': 0.4_8_5, 'label': 'cat'},
                        {'score': 0.0_0_4, 'label': 'plane'},
                    ],
                ]
                * 5    ,   )







       @slow
       @require_tf
       def       snake_case (				self      :			List[Any]   ):







            """simple docstring"""







            __lowercase      		=pipeline(
                task='zero-shot-image-classification'    ,   model='openai/clip-vit-base-patch32'    ,   framework='tf'   )
            # This is an image of 2 cats with remotes and no planes
            __lowercase      		=Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'   )
            __lowercase      		=image_classifier(__lowercase    ,   candidate_labels=['cat', 'plane', 'remote']   )
            self.assertEqual(
                nested_simplify(__lowercase   )    ,   [
                    {'score': 0.5_1_1, 'label': 'remote'},
                    {'score': 0.4_8_5, 'label': 'cat'},
                    {'score': 0.0_0_4, 'label': 'plane'},
                ]    ,   )

            __lowercase      		=image_classifier([image] * 5    ,   candidate_labels=['cat', 'plane', 'remote']    ,   batch_size=2   )
            self.assertEqual(
                nested_simplify(__lowercase   )    ,   [
                    [
                        {'score': 0.5_1_1, 'label': 'remote'},
                        {'score': 0.4_8_5, 'label': 'cat'},
                        {'score': 0.0_0_4, 'label': 'plane'},
                    ],
                ]
                * 5    ,   )





'''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


UpperCAmelCase					 =	get_tests_dir('''fixtures''')


class 	lowerCAmelCase  (   unittest.TestCase ):







       def       snake_case (				self      :			str   ):







            """simple docstring"""







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

            # Download this model to make sure it's in the cache.
            __lowercase      		=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:
                 __lowercase      		=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      :			Dict   ):







            """simple docstring"""







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






@is_staging_test
class 	lowerCAmelCase  (   unittest.TestCase ):







       @classmethod
       def       snake_case (				cls      :			str   ):







            """simple docstring"""







            __lowercase      		=TOKEN
            HfFolder.save_token(__lowercase   )







       @classmethod
       def       snake_case (				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       snake_case (				self      :			int   ):







            """simple docstring"""







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

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

            __lowercase      		=WavaVecaFeatureExtractor.from_pretrained(f'''{USER}/test-feature-extractor'''   )
            for k, v in feature_extractor.__dict__.items():
                 self.assertEqual(__lowercase    ,   getattr(__lowercase    ,   __lowercase   )   )







       def       snake_case (				self      :			List[Any]   ):







            """simple docstring"""







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

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

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







       def       snake_case (				self      :			Optional[Any]   ):







            """simple docstring"""







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

            __lowercase      		=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'   )


