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


UpperCamelCase_       :    Optional[int]						      =			get_tests_dir('''fixtures''')



class __lowerCAmelCase					(       unittest.TestCase   ):




			"""simple docstring"""







			def   lowerCamelCase__  (					self    :       str						)   ->			Any:







								"""simple docstring"""
								# A mock response for an HTTP head request to emulate server down
								A_								=    mock.Mock()
								A_								=    500
								A_								=    {}
								A_								=    HTTPError
								A_								=    {}

								# Download this model to make sure it's in the cache.
								A_								=    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=_snake_case						) as mock_head:
													A_								=    ViTImageProcessor.from_pretrained("hf-internal-testing/tiny-random-vit"						)
													# This check we did call the fake head request
													mock_head.assert_called()




			def   lowerCamelCase__  (					self    :       Optional[int]						)   ->			List[str]:







								"""simple docstring"""
								# This test is for deprecated behavior and can be removed in v5
								A_								=    ViTImageProcessor.from_pretrained(
								    "https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json"						)






			def   lowerCamelCase__  (					self    :       int						)   ->			int:







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

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

								self.assertIsNotNone(_snake_case						)





@is_staging_test
class __lowerCAmelCase					(       unittest.TestCase   ):




			"""simple docstring"""







			@classmethod
			def   lowerCamelCase__  (					cls    :       Any						)   ->			List[Any]:







								"""simple docstring"""
								A_								=    TOKEN
								HfFolder.save_token(_snake_case						)




			@classmethod
			def   lowerCamelCase__  (					cls    :       Tuple						)   ->			Optional[Any]:







								"""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   lowerCamelCase__  (					self    :       List[str]						)   ->			Optional[int]:







								"""simple docstring"""
								A_								=    ViTImageProcessor.from_pretrained(_snake_case						)
								image_processor.push_to_hub("test-image-processor"							, use_auth_token=self._token						)

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

								# 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(
													    _snake_case							, repo_id="test-image-processor"							, push_to_hub=_snake_case							, use_auth_token=self._token						)

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




			def   lowerCamelCase__  (					self    :       Dict						)   ->			Tuple:







								"""simple docstring"""
								A_								=    ViTImageProcessor.from_pretrained(_snake_case						)
								image_processor.push_to_hub("valid_org/test-image-processor"							, use_auth_token=self._token						)

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

								# 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(
													    _snake_case							, repo_id="valid_org/test-image-processor-org"							, push_to_hub=_snake_case							, use_auth_token=self._token						)

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






			def   lowerCamelCase__  (					self    :       str						)   ->			Optional[Any]:







								"""simple docstring"""
								CustomImageProcessor.register_for_auto_class()
								A_								=    CustomImageProcessor.from_pretrained(_snake_case						)

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

								A_								=    AutoImageProcessor.from_pretrained(
								    F'{USER}/test-dynamic-image-processor'							, trust_remote_code=_snake_case						)
								# 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"						)






"""simple docstring"""





import unittest

import numpy as np

from diffusers import LMSDiscreteScheduler, OnnxStableDiffusionInpaintPipeline
from diffusers.utils.testing_utils import (
    is_onnx_available,
    load_image,
    nightly,
    require_onnxruntime,
    require_torch_gpu,
)

from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin


if is_onnx_available():
		import onnxruntime as ort



class __lowerCAmelCase					(       _lowercase  ,					unittest.TestCase   ):




			"""simple docstring"""







			pass





@nightly
@require_onnxruntime
@require_torch_gpu
class __lowerCAmelCase					(       unittest.TestCase   ):




			"""simple docstring"""







			@property
			def   lowerCamelCase__  (					self    :       Union[str, Any]						)   ->			Dict:







								"""simple docstring"""
								return (
								    "CUDAExecutionProvider",
								    {
								        "gpu_mem_limit": "15000000000",  # 15GB
								        "arena_extend_strategy": "kSameAsRequested",
								    },
								)




			@property
			def   lowerCamelCase__  (					self    :       List[str]						)   ->			List[Any]:







								"""simple docstring"""
								A_								=    ort.SessionOptions()
								A_								=    False
								return options




			def   lowerCamelCase__  (					self    :       List[str]						)   ->			List[Any]:







								"""simple docstring"""
								A_								=    load_image(
								    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
								    "/in_paint/overture-creations-5sI6fQgYIuo.png"						)
								A_								=    load_image(
								    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
								    "/in_paint/overture-creations-5sI6fQgYIuo_mask.png"						)
								A_								=    OnnxStableDiffusionInpaintPipeline.from_pretrained(
								    "runwayml/stable-diffusion-inpainting"							, revision="onnx"							, safety_checker=_snake_case							, feature_extractor=_snake_case							, provider=self.gpu_provider							, sess_options=self.gpu_options							, )
								pipe.set_progress_bar_config(disable=_snake_case						)

								A_								=    "A red cat sitting on a park bench"

								A_								=    np.random.RandomState(0						)
								A_								=    pipe(
								    prompt=_snake_case							, image=_snake_case							, mask_image=_snake_case							, guidance_scale=7.5							, num_inference_steps=10							, generator=_snake_case							, output_type="np"							, )
								A_								=    output.images
								A_								=    images[0, 255:258, 255:258, -1]

								assert images.shape == (1, 512, 512, 3)
								A_								=    np.array([0.2_5_1_4, 0.3_0_0_7, 0.3_5_1_7, 0.1_7_9_0, 0.2_3_8_2, 0.3_1_6_7, 0.1_9_4_4, 0.2_2_7_3, 0.2_4_6_4]						)

								assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-3






			def   lowerCamelCase__  (					self    :       Optional[int]						)   ->			Tuple:







								"""simple docstring"""
								A_								=    load_image(
								    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
								    "/in_paint/overture-creations-5sI6fQgYIuo.png"						)
								A_								=    load_image(
								    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
								    "/in_paint/overture-creations-5sI6fQgYIuo_mask.png"						)
								A_								=    LMSDiscreteScheduler.from_pretrained(
								    "runwayml/stable-diffusion-inpainting"							, subfolder="scheduler"							, revision="onnx"						)
								A_								=    OnnxStableDiffusionInpaintPipeline.from_pretrained(
								    "runwayml/stable-diffusion-inpainting"							, revision="onnx"							, scheduler=_snake_case							, safety_checker=_snake_case							, feature_extractor=_snake_case							, provider=self.gpu_provider							, sess_options=self.gpu_options							, )
								pipe.set_progress_bar_config(disable=_snake_case						)

								A_								=    "A red cat sitting on a park bench"

								A_								=    np.random.RandomState(0						)
								A_								=    pipe(
								    prompt=_snake_case							, image=_snake_case							, mask_image=_snake_case							, guidance_scale=7.5							, num_inference_steps=20							, generator=_snake_case							, output_type="np"							, )
								A_								=    output.images
								A_								=    images[0, 255:258, 255:258, -1]

								assert images.shape == (1, 512, 512, 3)
								A_								=    np.array([0.0_0_8_6, 0.0_0_7_7, 0.0_0_8_3, 0.0_0_9_3, 0.0_1_0_7, 0.0_1_3_9, 0.0_0_9_4, 0.0_0_9_7, 0.0_1_2_5]						)

								assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-3




