

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 AutoImageProcessor, ViTImageProcessor
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_image_processing import CustomImageProcessor  # noqa E402


_a:    List[Any] 							=			get_tests_dir("""fixtures""")

class 						__UpperCamelCase    (					unittest.TestCase						):




	def       __A					(		self	:						Union[str, Any]							):


		'''simple docstring'''







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

		# Download this model to make sure it's in the cache.
		UpperCAmelCase_       				=			ViTImageProcessor.from_pretrained("hf-internal-testing/tiny-random-vit"							)
		# Under the mock environment we get a 500 error when trying to reach the model.
		with mock.patch("requests.Session.request"		,	return_value=lowerCAmelCase							) as mock_head:
			UpperCAmelCase_       				=			ViTImageProcessor.from_pretrained("hf-internal-testing/tiny-random-vit"							)
			# This check we did call the fake head request
			mock_head.assert_called()




	def       __A					(		self	:						List[str]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			ViTImageProcessor.from_pretrained(
		    "https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json"							)




	def       __A					(		self	:						Union[str, Any]							):


		'''simple docstring'''







		with self.assertRaises(lowerCAmelCase							):
			# config is in subfolder, the following should not work without specifying the subfolder
			UpperCAmelCase_       				=			AutoImageProcessor.from_pretrained("hf-internal-testing/stable-diffusion-all-variants"							)

		UpperCAmelCase_       				=			AutoImageProcessor.from_pretrained(
		    "hf-internal-testing/stable-diffusion-all-variants"		,	subfolder="feature_extractor"							)

		self.assertIsNotNone(lowerCAmelCase							)


@is_staging_test
class 						__UpperCamelCase    (					unittest.TestCase						):




	@classmethod
	def       __A					(		cls	:						Dict							):


		'''simple docstring'''







		UpperCAmelCase_       				=			TOKEN
		HfFolder.save_token(lowerCAmelCase							)




	@classmethod
	def       __A					(		cls	:						List[str]							):


		'''simple docstring'''







		try:
			delete_repo(token=cls._token		,	repo_id="test-image-processor"							)
		except HTTPError:
			pass

		try:
			delete_repo(token=cls._token		,	repo_id="valid_org/test-image-processor-org"							)
		except HTTPError:
			pass

		try:
			delete_repo(token=cls._token		,	repo_id="test-dynamic-image-processor"							)
		except HTTPError:
			pass




	def       __A					(		self	:						Union[str, Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			ViTImageProcessor.from_pretrained(lowerCAmelCase							)
		image_processor.push_to_hub("test-image-processor"		,	use_auth_token=self._token							)

		UpperCAmelCase_       				=			ViTImageProcessor.from_pretrained(F"{USER}/test-image-processor"							)
		for k, v in image_processor.__dict__.items():
			self.assertEqual(lowerCAmelCase		,	getattr(lowerCAmelCase		,	lowerCAmelCase							)							)

		# Reset repo
		delete_repo(token=self._token		,	repo_id="test-image-processor"							)

		# Push to hub via save_pretrained
		with tempfile.TemporaryDirectory() as tmp_dir:
			image_processor.save_pretrained(
			    lowerCAmelCase		,	repo_id="test-image-processor"		,	push_to_hub=lowerCAmelCase		,	use_auth_token=self._token							)

		UpperCAmelCase_       				=			ViTImageProcessor.from_pretrained(F"{USER}/test-image-processor"							)
		for k, v in image_processor.__dict__.items():
			self.assertEqual(lowerCAmelCase		,	getattr(lowerCAmelCase		,	lowerCAmelCase							)							)




	def       __A					(		self	:						Optional[Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			ViTImageProcessor.from_pretrained(lowerCAmelCase							)
		image_processor.push_to_hub("valid_org/test-image-processor"		,	use_auth_token=self._token							)

		UpperCAmelCase_       				=			ViTImageProcessor.from_pretrained("valid_org/test-image-processor"							)
		for k, v in image_processor.__dict__.items():
			self.assertEqual(lowerCAmelCase		,	getattr(lowerCAmelCase		,	lowerCAmelCase							)							)

		# Reset repo
		delete_repo(token=self._token		,	repo_id="valid_org/test-image-processor"							)

		# Push to hub via save_pretrained
		with tempfile.TemporaryDirectory() as tmp_dir:
			image_processor.save_pretrained(
			    lowerCAmelCase		,	repo_id="valid_org/test-image-processor-org"		,	push_to_hub=lowerCAmelCase		,	use_auth_token=self._token							)

		UpperCAmelCase_       				=			ViTImageProcessor.from_pretrained("valid_org/test-image-processor-org"							)
		for k, v in image_processor.__dict__.items():
			self.assertEqual(lowerCAmelCase		,	getattr(lowerCAmelCase		,	lowerCAmelCase							)							)




	def       __A					(		self	:						int							):


		'''simple docstring'''







		CustomImageProcessor.register_for_auto_class()
		UpperCAmelCase_       				=			CustomImageProcessor.from_pretrained(lowerCAmelCase							)

		image_processor.push_to_hub("test-dynamic-image-processor"		,	use_auth_token=self._token							)

		# This has added the proper auto_map field to the config
		self.assertDictEqual(
		    image_processor.auto_map		,	{"AutoImageProcessor": "custom_image_processing.CustomImageProcessor"}		,	)

		UpperCAmelCase_       				=			AutoImageProcessor.from_pretrained(
		    F"{USER}/test-dynamic-image-processor"		,	trust_remote_code=lowerCAmelCase							)
		# Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module
		self.assertEqual(new_image_processor.__class__.__name__		,	"CustomImageProcessor"							)


from sklearn.metrics import mean_squared_error

import datasets


_a:    Any 							=			"""\
@article{scikit-learn,
 title={Scikit-learn: Machine Learning in {P}ython},
 author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.
         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.
         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and
         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},
 journal={Journal of Machine Learning Research},
 volume={12},
 pages={2825--2830},
 year={2011}
}
"""

_a:    List[Any] 							=			"""\
Mean Squared Error(MSE) is the average of the square of difference between the predicted
and actual values.
"""


_a:    List[str] 							=			"""
Args:
    predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)
        Estimated target values.
    references: array-like of shape (n_samples,) or (n_samples, n_outputs)
        Ground truth (correct) target values.
    sample_weight: array-like of shape (n_samples,), default=None
        Sample weights.
    multioutput: {\"raw_values\", \"uniform_average\"} or array-like of shape (n_outputs,), default=\"uniform_average\"
        Defines aggregating of multiple output values. Array-like value defines weights used to average errors.

        \"raw_values\" : Returns a full set of errors in case of multioutput input.

        \"uniform_average\" : Errors of all outputs are averaged with uniform weight.

    squared : bool, default=True
        If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value.

Returns:
    mse : mean squared error.
Examples:

    >>> mse_metric = datasets.load_metric(\"mse\")
    >>> predictions = [2.5, 0.0, 2, 8]
    >>> references = [3, -0.5, 2, 7]
    >>> results = mse_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'mse': 0.375}
    >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False)
    >>> print(rmse_result)
    {'mse': 0.6123724356957945}

    If you're using multi-dimensional lists, then set the config as follows :

    >>> mse_metric = datasets.load_metric(\"mse\", \"multilist\")
    >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]
    >>> references = [[0, 2], [-1, 2], [8, -5]]
    >>> results = mse_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'mse': 0.7083333333333334}
    >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput='raw_values')
    >>> print(results) # doctest: +NORMALIZE_WHITESPACE
    {'mse': array([0.41666667, 1. ])}
"""

@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION     ,     _KWARGS_DESCRIPTION						)
class 						__UpperCamelCase    (					datasets.Metric						):




	def       __A					(		self	:						List[str]							):


		'''simple docstring'''







		return datasets.MetricInfo(
		    description=_DESCRIPTION		,	citation=_CITATION		,	inputs_description=_KWARGS_DESCRIPTION		,	features=datasets.Features(self._get_feature_types()							)		,	reference_urls=[
		        "https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html"
		    ]		,	)




	def       __A					(		self	:						Optional[Any]							):


		'''simple docstring'''







		if self.config_name == "multilist":
			return {
			    "predictions": datasets.Sequence(datasets.Value("float"							)							),
			    "references": datasets.Sequence(datasets.Value("float"							)							),
			}
		else:
			return {
			    "predictions": datasets.Value("float"							),
			    "references": datasets.Value("float"							),
			}




	def       __A					(		self	:						Tuple		,	lowerCAmelCase	:						int		,	lowerCAmelCase	:						Dict		,	lowerCAmelCase	:						str=None		,	lowerCAmelCase	:						str="uniform_average"		,	lowerCAmelCase	:						Any=True							):


		'''simple docstring'''







		UpperCAmelCase_       				=			mean_squared_error(
		    lowerCAmelCase		,	lowerCAmelCase		,	sample_weight=lowerCAmelCase		,	multioutput=lowerCAmelCase		,	squared=lowerCAmelCase							)

		return {"mse": mse}