




import importlib
import json
import os
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
import transformers.models.auto
from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig
from transformers.models.bert.configuration_bert import BertConfig
from transformers.models.roberta.configuration_roberta import RobertaConfig
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir


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

from test_module.custom_configuration import CustomConfig  # noqa E402


__a    :						str						      =       get_tests_dir('''fixtures/dummy-config.json''')







class  UpperCAmelCase(	unittest.TestCase	):



	"""simple docstring"""






	def        __a      (	self							)   ->     Optional[int]:





								"""simple docstring"""


								lowercase__    :			Any     =				0

	def        __a      (	self							)   ->     str:





								"""simple docstring"""


								self.assertIsNotNone(transformers.models.auto.__spec__							)
								self.assertIsNotNone(importlib.util.find_spec("transformers.models.auto"							)							)

	def        __a      (	self							)   ->     Tuple:





								"""simple docstring"""


								lowercase__    :			str     =				AutoConfig.from_pretrained("bert-base-uncased"							)
								self.assertIsInstance(snake_case_			, snake_case_							)

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





								"""simple docstring"""


								lowercase__    :			Dict     =				AutoConfig.from_pretrained(snake_case_							)
								self.assertIsInstance(snake_case_			, snake_case_							)

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





								"""simple docstring"""


								lowercase__    :			List[Any]     =				AutoConfig.from_pretrained(snake_case_							)
								self.assertIsInstance(snake_case_			, snake_case_							)

	def        __a      (	self							)   ->     Any:





								"""simple docstring"""


								lowercase__    :			Any     =				AutoConfig.for_model("roberta"							)
								self.assertIsInstance(snake_case_			, snake_case_							)

	def        __a      (	self							)   ->     Dict:





								"""simple docstring"""


								with tempfile.TemporaryDirectory() as tmp_dir:
															# This model name contains bert and roberta, but roberta ends up being picked.
															lowercase__    :			int     =				os.path.join(snake_case_			, "fake-roberta"							)
															os.makedirs(snake_case_			, exist_ok=snake_case_							)
															with open(os.path.join(snake_case_			, "config.json"							)			, "w"							) as f:
																						f.write(json.dumps({}							)							)
															lowercase__    :			Union[str, Any]     =				AutoConfig.from_pretrained(snake_case_							)
															self.assertEqual(type(snake_case_							)			, snake_case_							)

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





								"""simple docstring"""


								try:
															AutoConfig.register("custom"			, snake_case_							)
															# Wrong model type will raise an error
															with self.assertRaises(snake_case_							):
																						AutoConfig.register("model"			, snake_case_							)
															# Trying to register something existing in the Transformers library will raise an error
															with self.assertRaises(snake_case_							):
																						AutoConfig.register("bert"			, snake_case_							)

															# Now that the config is registered, it can be used as any other config with the auto-API
															lowercase__    :			str     =				CustomConfig()
															with tempfile.TemporaryDirectory() as tmp_dir:
																						config.save_pretrained(snake_case_							)
																						lowercase__    :			List[str]     =				AutoConfig.from_pretrained(snake_case_							)
																						self.assertIsInstance(snake_case_			, snake_case_							)

								finally:
															if "custom" in CONFIG_MAPPING._extra_content:
																						del CONFIG_MAPPING._extra_content["custom"]

	def        __a      (	self							)   ->     str:





								"""simple docstring"""


								with self.assertRaisesRegex(
								    snake_case_			, "bert-base is not a local folder and is not a valid model identifier"							):
															lowercase__    :			List[Any]     =				AutoConfig.from_pretrained("bert-base"							)

	def        __a      (	self							)   ->     Any:





								"""simple docstring"""


								with self.assertRaisesRegex(
								    snake_case_			, r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"							):
															lowercase__    :			Optional[int]     =				AutoConfig.from_pretrained(snake_case_			, revision="aaaaaa"							)

	def        __a      (	self							)   ->     Any:





								"""simple docstring"""


								with self.assertRaisesRegex(
								    snake_case_			, "hf-internal-testing/no-config-test-repo does not appear to have a file named config.json."			, ):
															lowercase__    :			Dict     =				AutoConfig.from_pretrained("hf-internal-testing/no-config-test-repo"							)

	def        __a      (	self							)   ->     Dict:





								"""simple docstring"""


								with self.assertRaises(snake_case_							):
															lowercase__    :			Tuple     =				AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"							)
								# If remote code is disabled, we can't load this config.
								with self.assertRaises(snake_case_							):
															lowercase__    :			Dict     =				AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"			, trust_remote_code=snake_case_							)

								lowercase__    :			Union[str, Any]     =				AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"			, trust_remote_code=snake_case_							)
								self.assertEqual(config.__class__.__name__			, "NewModelConfig"							)

								# Test config can be reloaded.
								with tempfile.TemporaryDirectory() as tmp_dir:
															config.save_pretrained(snake_case_							)
															lowercase__    :			Union[str, Any]     =				AutoConfig.from_pretrained(snake_case_			, trust_remote_code=snake_case_							)
								self.assertEqual(reloaded_config.__class__.__name__			, "NewModelConfig"							)







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





								"""simple docstring"""


								class  UpperCAmelCase(	snake_case_	):



									"""simple docstring"""






									a      :   List[str]			    =	"""new-model"""

								try:
															AutoConfig.register("new-model"			, snake_case_							)
															# If remote code is not set, the default is to use local
															lowercase__    :			Dict     =				AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"							)
															self.assertEqual(config.__class__.__name__			, "NewModelConfigLocal"							)

															# If remote code is disabled, we load the local one.
															lowercase__    :			Any     =				AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"			, trust_remote_code=snake_case_							)
															self.assertEqual(config.__class__.__name__			, "NewModelConfigLocal"							)

															# If remote is enabled, we load from the Hub
															lowercase__    :			Dict     =				AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"			, trust_remote_code=snake_case_							)
															self.assertEqual(config.__class__.__name__			, "NewModelConfig"							)

								finally:
															if "new-model" in CONFIG_MAPPING._extra_content:
																						del CONFIG_MAPPING._extra_content["new-model"]




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     __a			:



					@staticmethod
					def 		UpperCamelCase				(    *snake_case_				:     Any					,						**snake_case_				:     str)->				int:
										pass






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



	@require_torch
	def 		UpperCamelCase				(    self				:     Dict)->				List[str]:
						__lowerCAmelCase						 =pipeline(
						    model="""hf-internal-testing/tiny-random-clip-zero-shot-image-classification"""					,						)
						__lowerCAmelCase						 =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""")
						__lowerCAmelCase						 =image_classifier(snake_case_					,						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(snake_case_)					,						[
						        [{"""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"""}],
						    ]					,						)

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



	@require_tf
	def 		UpperCamelCase				(    self				:     Dict)->				Optional[Any]:
						__lowerCAmelCase						 =pipeline(
						    model="""hf-internal-testing/tiny-random-clip-zero-shot-image-classification"""					,						framework="""tf""")
						__lowerCAmelCase						 =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""")
						__lowerCAmelCase						 =image_classifier(snake_case_					,						candidate_labels=["""a""", """b""", """c"""])

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

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



	@slow
	@require_torch
	def 		UpperCamelCase				(    self				:     Any)->				Dict:
						__lowerCAmelCase						 =pipeline(
						    task="""zero-shot-image-classification"""					,						model="""openai/clip-vit-base-patch32"""					,						)
						# This is an image of 2 cats with remotes and no planes
						__lowerCAmelCase						 =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""")
						__lowerCAmelCase						 =image_classifier(snake_case_					,						candidate_labels=["""cat""", """plane""", """remote"""])

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

						__lowerCAmelCase						 =image_classifier([image] * 5					,						candidate_labels=["""cat""", """plane""", """remote"""]					,						batch_size=2)
						self.assertEqual(
						    nested_simplify(snake_case_)					,						[
						        [
						            {"""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 		UpperCamelCase				(    self				:     Optional[int])->				int:
						__lowerCAmelCase						 =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
						__lowerCAmelCase						 =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""")
						__lowerCAmelCase						 =image_classifier(snake_case_					,						candidate_labels=["""cat""", """plane""", """remote"""])
						self.assertEqual(
						    nested_simplify(snake_case_)					,						[
						        {"""score""": 0.5_1_1, """label""": """remote"""},
						        {"""score""": 0.4_8_5, """label""": """cat"""},
						        {"""score""": 0.0_0_4, """label""": """plane"""},
						    ]					,						)

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




