

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

import transformers
from transformers import (
    CONFIG_MAPPING,
    IMAGE_PROCESSOR_MAPPING,
    AutoConfig,
    AutoImageProcessor,
    CLIPConfig,
    CLIPImageProcessor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER


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

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_image_processing import CustomImageProcessor  # noqa E402

class 						__UpperCamelCase    (					unittest.TestCase						):




	def       __A					(		self	:						Optional[int]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			0




	def       __A					(		self	:						Tuple							):


		'''simple docstring'''







		UpperCAmelCase_       				=			AutoImageProcessor.from_pretrained("openai/clip-vit-base-patch32"							)
		self.assertIsInstance(lowerCAmelCase		,	lowerCAmelCase							)




	def       __A					(		self	:						int							):


		'''simple docstring'''







		with tempfile.TemporaryDirectory() as tmpdirname:
			UpperCAmelCase_       				=			Path(lowerCAmelCase							) / "preprocessor_config.json"
			UpperCAmelCase_       				=			Path(lowerCAmelCase							) / "config.json"
			json.dump(
			    {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"}		,	open(lowerCAmelCase		,	"w"							)		,	)
			json.dump({"model_type": "clip"}		,	open(lowerCAmelCase		,	"w"							)							)

			UpperCAmelCase_       				=			AutoImageProcessor.from_pretrained(lowerCAmelCase							)
			self.assertIsInstance(lowerCAmelCase		,	lowerCAmelCase							)




	def       __A					(		self	:						Optional[int]							):


		'''simple docstring'''







		with tempfile.TemporaryDirectory() as tmpdirname:
			UpperCAmelCase_       				=			Path(lowerCAmelCase							) / "preprocessor_config.json"
			UpperCAmelCase_       				=			Path(lowerCAmelCase							) / "config.json"
			json.dump(
			    {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"}		,	open(lowerCAmelCase		,	"w"							)		,	)
			json.dump({"model_type": "clip"}		,	open(lowerCAmelCase		,	"w"							)							)

			UpperCAmelCase_       				=			AutoImageProcessor.from_pretrained(lowerCAmelCase							)
			self.assertIsInstance(lowerCAmelCase		,	lowerCAmelCase							)




	def       __A					(		self	:						Any							):


		'''simple docstring'''







		with tempfile.TemporaryDirectory() as tmpdirname:
			UpperCAmelCase_       				=			CLIPConfig()

			# Create a dummy config file with image_proceesor_type
			UpperCAmelCase_       				=			Path(lowerCAmelCase							) / "preprocessor_config.json"
			UpperCAmelCase_       				=			Path(lowerCAmelCase							) / "config.json"
			json.dump(
			    {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"}		,	open(lowerCAmelCase		,	"w"							)		,	)
			json.dump({"model_type": "clip"}		,	open(lowerCAmelCase		,	"w"							)							)

			# remove image_processor_type to make sure config.json alone is enough to load image processor locally
			UpperCAmelCase_       				=			AutoImageProcessor.from_pretrained(lowerCAmelCase							).to_dict()

			config_dict.pop("image_processor_type"							)
			UpperCAmelCase_       				=			CLIPImageProcessor(**lowerCAmelCase							)

			# save in new folder
			model_config.save_pretrained(lowerCAmelCase							)
			config.save_pretrained(lowerCAmelCase							)

			UpperCAmelCase_       				=			AutoImageProcessor.from_pretrained(lowerCAmelCase							)

			# make sure private variable is not incorrectly saved
			UpperCAmelCase_       				=			json.loads(config.to_json_string()							)
			self.assertTrue("_processor_class" not in dict_as_saved							)

		self.assertIsInstance(lowerCAmelCase		,	lowerCAmelCase							)




	def       __A					(		self	:						int							):


		'''simple docstring'''







		with tempfile.TemporaryDirectory() as tmpdirname:
			UpperCAmelCase_       				=			Path(lowerCAmelCase							) / "preprocessor_config.json"
			json.dump(
			    {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"}		,	open(lowerCAmelCase		,	"w"							)		,	)

			UpperCAmelCase_       				=			AutoImageProcessor.from_pretrained(lowerCAmelCase							)
			self.assertIsInstance(lowerCAmelCase		,	lowerCAmelCase							)




	def       __A					(		self	:						Tuple							):


		'''simple docstring'''







		with self.assertRaisesRegex(
		    lowerCAmelCase		,	"clip-base is not a local folder and is not a valid model identifier"							):
			UpperCAmelCase_       				=			AutoImageProcessor.from_pretrained("clip-base"							)




	def       __A					(		self	:						Dict							):


		'''simple docstring'''







		with self.assertRaisesRegex(
		    lowerCAmelCase		,	R"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"							):
			UpperCAmelCase_       				=			AutoImageProcessor.from_pretrained(lowerCAmelCase		,	revision="aaaaaa"							)




	def       __A					(		self	:						Dict							):


		'''simple docstring'''







		with self.assertRaisesRegex(
		    lowerCAmelCase		,	"hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json."		,	):
			UpperCAmelCase_       				=			AutoImageProcessor.from_pretrained("hf-internal-testing/config-no-model"							)




	def       __A					(		self	:						int							):


		'''simple docstring'''







		with self.assertRaises(lowerCAmelCase							):
			UpperCAmelCase_       				=			AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor"							)
		# If remote code is disabled, we can't load this config.
		with self.assertRaises(lowerCAmelCase							):
			UpperCAmelCase_       				=			AutoImageProcessor.from_pretrained(
			    "hf-internal-testing/test_dynamic_image_processor"		,	trust_remote_code=lowerCAmelCase							)

		UpperCAmelCase_       				=			AutoImageProcessor.from_pretrained(
		    "hf-internal-testing/test_dynamic_image_processor"		,	trust_remote_code=lowerCAmelCase							)
		self.assertEqual(image_processor.__class__.__name__		,	"NewImageProcessor"							)

		# Test image processor can be reloaded.
		with tempfile.TemporaryDirectory() as tmp_dir:
			image_processor.save_pretrained(lowerCAmelCase							)
			UpperCAmelCase_       				=			AutoImageProcessor.from_pretrained(lowerCAmelCase		,	trust_remote_code=lowerCAmelCase							)
		self.assertEqual(reloaded_image_processor.__class__.__name__		,	"NewImageProcessor"							)




	def       __A					(		self	:						Optional[Any]							):


		'''simple docstring'''







		try:
			AutoConfig.register("custom"		,	lowerCAmelCase							)
			AutoImageProcessor.register(lowerCAmelCase		,	lowerCAmelCase							)
			# Trying to register something existing in the Transformers library will raise an error
			with self.assertRaises(lowerCAmelCase							):
				AutoImageProcessor.register(lowerCAmelCase		,	lowerCAmelCase							)

			with tempfile.TemporaryDirectory() as tmpdirname:
				UpperCAmelCase_       				=			Path(lowerCAmelCase							) / "preprocessor_config.json"
				UpperCAmelCase_       				=			Path(lowerCAmelCase							) / "config.json"
				json.dump(
				    {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"}		,	open(lowerCAmelCase		,	"w"							)		,	)
				json.dump({"model_type": "clip"}		,	open(lowerCAmelCase		,	"w"							)							)

				UpperCAmelCase_       				=			CustomImageProcessor.from_pretrained(lowerCAmelCase							)

			# Now that the config is registered, it can be used as any other config with the auto-API
			with tempfile.TemporaryDirectory() as tmp_dir:
				image_processor.save_pretrained(lowerCAmelCase							)
				UpperCAmelCase_       				=			AutoImageProcessor.from_pretrained(lowerCAmelCase							)
				self.assertIsInstance(lowerCAmelCase		,	lowerCAmelCase							)

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




	def       __A					(		self	:						Optional[Any]							):


		'''simple docstring'''







		class 						__UpperCamelCase    (					lowercase						):
			SCREAMING_SNAKE_CASE__    				=     True

		try:
			AutoConfig.register("custom"		,	lowerCAmelCase							)
			AutoImageProcessor.register(lowerCAmelCase		,	lowerCAmelCase							)
			# If remote code is not set, the default is to use local
			UpperCAmelCase_       				=			AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor"							)
			self.assertEqual(image_processor.__class__.__name__		,	"NewImageProcessor"							)
			self.assertTrue(image_processor.is_local							)

			# If remote code is disabled, we load the local one.
			UpperCAmelCase_       				=			AutoImageProcessor.from_pretrained(
			    "hf-internal-testing/test_dynamic_image_processor"		,	trust_remote_code=lowerCAmelCase							)
			self.assertEqual(image_processor.__class__.__name__		,	"NewImageProcessor"							)
			self.assertTrue(image_processor.is_local							)

			# If remote is enabled, we load from the Hub
			UpperCAmelCase_       				=			AutoImageProcessor.from_pretrained(
			    "hf-internal-testing/test_dynamic_image_processor"		,	trust_remote_code=lowerCAmelCase							)
			self.assertEqual(image_processor.__class__.__name__		,	"NewImageProcessor"							)
			self.assertTrue(not hasattr(lowerCAmelCase		,	"is_local"							)							)

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


def       __lowerCAmelCase      (						A    ):
	UpperCAmelCase_       				=			generate_pascal_triangle(A    )
	for row_idx in range(A    ):
		# Print left spaces
		for _ in range(num_rows - row_idx - 1    ):
			print(end=" "    )
		# Print row values
		for col_idx in range(row_idx + 1    ):
			if col_idx != row_idx:
				print(triangle[row_idx][col_idx]       ,     end=" "    )
			else:
				print(triangle[row_idx][col_idx]       ,     end=""    )
		print()



def       __lowerCAmelCase      (						A    ):

	if not isinstance(A       ,     A    ):
		raise TypeError("The input value of 'num_rows' should be 'int'"    )

	if num_rows == 0:
		return []
	elif num_rows < 0:
		raise ValueError(
		    "The input value of 'num_rows' should be greater than or equal to 0"    )

	UpperCAmelCase_       				=			[]
	for current_row_idx in range(A    ):
		UpperCAmelCase_       				=			populate_current_row(A       ,     A    )
		triangle.append(A    )
	return triangle



def       __lowerCAmelCase      (						A       ,     A    ):
	UpperCAmelCase_       				=			[-1] * (current_row_idx + 1)
	# first and last elements of current row are equal to 1
	UpperCAmelCase_				,   UpperCAmelCase_       				=			1, 1
	for current_col_idx in range(1       ,     A    ):
		calculate_current_element(
		    A       ,     A       ,     A       ,     A    )
	return current_row



def       __lowerCAmelCase      (						A       ,     A       ,     A       ,     A       ,     ):
	UpperCAmelCase_       				=			triangle[current_row_idx - 1][current_col_idx - 1]
	UpperCAmelCase_       				=			triangle[current_row_idx - 1][current_col_idx]
	UpperCAmelCase_       				=			above_to_left_elt + above_to_right_elt



def       __lowerCAmelCase      (						A    ):

	if not isinstance(A       ,     A    ):
		raise TypeError("The input value of 'num_rows' should be 'int'"    )

	if num_rows == 0:
		return []
	elif num_rows < 0:
		raise ValueError(
		    "The input value of 'num_rows' should be greater than or equal to 0"    )

	UpperCAmelCase_       				=			[[1]]

	for row_index in range(1       ,     A    ):
		UpperCAmelCase_       				=			[0] + result[-1] + [0]
		UpperCAmelCase_       				=			row_index + 1
		# Calculate the number of distinct elements in a row
		UpperCAmelCase_       				=			sum(divmod(A       ,     2    )    )
		UpperCAmelCase_       				=			[
		    temp_row[i - 1] + temp_row[i] for i in range(1       ,     distinct_elements + 1    )
		]
		UpperCAmelCase_       				=			row_first_half[: (row_index + 1) // 2]
		row_second_half.reverse()
		UpperCAmelCase_       				=			row_first_half + row_second_half
		result.append(A    )

	return result



def       __lowerCAmelCase      (						):
	from collections.abc import Callable
	from timeit import timeit

	def benchmark_a_function(A       ,     A    ) -> None:
		UpperCAmelCase_       				=			F"{func.__name__}({value})"
		UpperCAmelCase_       				=			timeit(F"__main__.{call}"       ,     setup="import __main__"    )
		# print(f"{call:38} = {func(value)} -- {timing:.4f} seconds")
		print(F"{call:38} -- {timing:.4f} seconds"    )

	for value in range(15    ):  # (1, 7, 14):
		for func in (generate_pascal_triangle, generate_pascal_triangle_optimized):
			benchmark_a_function(A       ,     A    )
		print()


if __name__ == "__main__":
				import doctest

				doctest.testmod()
				benchmark()