
import subprocess
import sys

from transformers import BertConfig, BertModel, BertTokenizer, pipeline
from transformers.testing_utils import TestCasePlus, require_torch

class     _UpperCamelCase			(   _A					):






			'''simple docstring'''

			@require_torch
			def  lowerCAmelCase__		(    self	:    List[Any] ):
							# this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before
							# `transformers` is loaded, and it's too late for inside pytest - so we are changing it
							# while running an external program

							# python one-liner segments

							# this must be loaded before socket.socket is monkey-patched
							UpperCamelCase_:							List[str]		=  """
from transformers import BertConfig, BertModel, BertTokenizer, pipeline
        """

							UpperCamelCase_:							Optional[Any]		=  """
mname = \"hf-internal-testing/tiny-random-bert\"
BertConfig.from_pretrained(mname)
BertModel.from_pretrained(mname)
BertTokenizer.from_pretrained(mname)
pipe = pipeline(task=\"fill-mask\", model=mname)
print(\"success\")
        """

							UpperCamelCase_:							List[Any]		=  """
import socket
def offline_socket(*args, **kwargs): raise RuntimeError(\"Offline mode is enabled, we shouldn't access internet\")
socket.socket = offline_socket
        """

							# Force fetching the files so that we can use the cache
							UpperCamelCase_:							List[str]		=  """hf-internal-testing/tiny-random-bert"""
							BertConfig.from_pretrained(snake_case_ )
							BertModel.from_pretrained(snake_case_ )
							BertTokenizer.from_pretrained(snake_case_ )
							pipeline(task="""fill-mask"""  ,		model=snake_case_ )

							# baseline - just load from_pretrained with normal network
							UpperCamelCase_:							str		=  [sys.executable, """-c""", """\n""".join([load, run, mock] )]

							# should succeed
							UpperCamelCase_:							Optional[int]		=  self.get_env()
							# should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
							UpperCamelCase_:							List[Any]		=  """1"""
							UpperCamelCase_:							List[Any]		=  subprocess.run(snake_case_  ,		env=snake_case_  ,		check=snake_case_  ,		capture_output=snake_case_ )
							self.assertEqual(result.returncode  ,		0  ,		result.stderr )
							self.assertIn("""success"""  ,		result.stdout.decode() )

			@require_torch
			def  lowerCAmelCase__		(    self	:    Dict ):
							# python one-liner segments
							# this must be loaded before socket.socket is monkey-patched
							UpperCamelCase_:							Any		=  """
from transformers import BertConfig, BertModel, BertTokenizer, pipeline
        """

							UpperCamelCase_:							Union[str, Any]		=  """
mname = \"hf-internal-testing/tiny-random-bert\"
BertConfig.from_pretrained(mname)
BertModel.from_pretrained(mname)
BertTokenizer.from_pretrained(mname)
pipe = pipeline(task=\"fill-mask\", model=mname)
print(\"success\")
        """

							UpperCamelCase_:							str		=  """
import socket
def offline_socket(*args, **kwargs): raise socket.error(\"Faking flaky internet\")
socket.socket = offline_socket
        """

							# Force fetching the files so that we can use the cache
							UpperCamelCase_:							Union[str, Any]		=  """hf-internal-testing/tiny-random-bert"""
							BertConfig.from_pretrained(snake_case_ )
							BertModel.from_pretrained(snake_case_ )
							BertTokenizer.from_pretrained(snake_case_ )
							pipeline(task="""fill-mask"""  ,		model=snake_case_ )

							# baseline - just load from_pretrained with normal network
							UpperCamelCase_:							Tuple		=  [sys.executable, """-c""", """\n""".join([load, run, mock] )]

							# should succeed
							UpperCamelCase_:							List[Any]		=  self.get_env()
							UpperCamelCase_:							List[str]		=  subprocess.run(snake_case_  ,		env=snake_case_  ,		check=snake_case_  ,		capture_output=snake_case_ )
							self.assertEqual(result.returncode  ,		0  ,		result.stderr )
							self.assertIn("""success"""  ,		result.stdout.decode() )

			@require_torch
			def  lowerCAmelCase__		(    self	:    List[Any] ):
							# this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before
							# `transformers` is loaded, and it's too late for inside pytest - so we are changing it
							# while running an external program

							# python one-liner segments

							# this must be loaded before socket.socket is monkey-patched
							UpperCamelCase_:							Tuple		=  """
from transformers import BertConfig, BertModel, BertTokenizer
        """

							UpperCamelCase_:							Optional[int]		=  """
mname = \"hf-internal-testing/tiny-random-bert-sharded\"
BertConfig.from_pretrained(mname)
BertModel.from_pretrained(mname)
print(\"success\")
        """

							UpperCamelCase_:							List[Any]		=  """
import socket
def offline_socket(*args, **kwargs): raise ValueError(\"Offline mode is enabled\")
socket.socket = offline_socket
        """

							# baseline - just load from_pretrained with normal network
							UpperCamelCase_:							Dict		=  [sys.executable, """-c""", """\n""".join([load, run] )]

							# should succeed
							UpperCamelCase_:							Any		=  self.get_env()
							UpperCamelCase_:							int		=  subprocess.run(snake_case_  ,		env=snake_case_  ,		check=snake_case_  ,		capture_output=snake_case_ )
							self.assertEqual(result.returncode  ,		0  ,		result.stderr )
							self.assertIn("""success"""  ,		result.stdout.decode() )

							# next emulate no network
							UpperCamelCase_:							Optional[int]		=  [sys.executable, """-c""", """\n""".join([load, mock, run] )]

							# Doesn't fail anymore since the model is in the cache due to other tests, so commenting this.
							# env["TRANSFORMERS_OFFLINE"] = "0"
							# result = subprocess.run(cmd, env=env, check=False, capture_output=True)
							# self.assertEqual(result.returncode, 1, result.stderr)

							# should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
							UpperCamelCase_:							Any		=  """1"""
							UpperCamelCase_:							Optional[int]		=  subprocess.run(snake_case_  ,		env=snake_case_  ,		check=snake_case_  ,		capture_output=snake_case_ )
							self.assertEqual(result.returncode  ,		0  ,		result.stderr )
							self.assertIn("""success"""  ,		result.stdout.decode() )

			@require_torch
			def  lowerCAmelCase__		(    self	:    Dict ):
							UpperCamelCase_:							Tuple		=  """
from transformers import pipeline
        """
							UpperCamelCase_:							Tuple		=  """
mname = \"hf-internal-testing/tiny-random-bert\"
pipe = pipeline(model=mname)
        """

							UpperCamelCase_:							Union[str, Any]		=  """
import socket
def offline_socket(*args, **kwargs): raise socket.error(\"Offline mode is enabled\")
socket.socket = offline_socket
        """
							UpperCamelCase_:							int		=  self.get_env()
							UpperCamelCase_:							int		=  """1"""
							UpperCamelCase_:							str		=  [sys.executable, """-c""", """\n""".join([load, mock, run] )]
							UpperCamelCase_:							Union[str, Any]		=  subprocess.run(snake_case_  ,		env=snake_case_  ,		check=snake_case_  ,		capture_output=snake_case_ )
							self.assertEqual(result.returncode  ,		1  ,		result.stderr )
							self.assertIn(
							    """You cannot infer task automatically within `pipeline` when using offline mode"""  ,		result.stderr.decode().replace("""\n"""  ,		"""""" )  ,		)




			@require_torch
			def  lowerCAmelCase__		(    self	:    Union[str, Any] ):
							UpperCamelCase_:							int		=  """
from transformers import AutoModel
        """
							UpperCamelCase_:							Tuple		=  """
mname = \"hf-internal-testing/test_dynamic_model\"
AutoModel.from_pretrained(mname, trust_remote_code=True)
print(\"success\")
        """

							# baseline - just load from_pretrained with normal network
							UpperCamelCase_:							List[str]		=  [sys.executable, """-c""", """\n""".join([load, run] )]

							# should succeed
							UpperCamelCase_:							List[str]		=  self.get_env()
							UpperCamelCase_:							Union[str, Any]		=  subprocess.run(snake_case_  ,		env=snake_case_  ,		check=snake_case_  ,		capture_output=snake_case_ )
							self.assertEqual(result.returncode  ,		0  ,		result.stderr )
							self.assertIn("""success"""  ,		result.stdout.decode() )

							# should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
							UpperCamelCase_:							List[Any]		=  """1"""
							UpperCamelCase_:							Optional[Any]		=  subprocess.run(snake_case_  ,		env=snake_case_  ,		check=snake_case_  ,		capture_output=snake_case_ )
							self.assertEqual(result.returncode  ,		0  ,		result.stderr )
							self.assertIn("""success"""  ,		result.stdout.decode() )








import random
import unittest

import numpy as np

from diffusers import (
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionImgaImgPipeline,
    PNDMScheduler,
)
from diffusers.utils import floats_tensor
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     _UpperCamelCase			(   _A       ,    unittest.TestCase					):






			'''simple docstring'''

			__UpperCamelCase :  Optional[Any]    =	"""hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline"""

			def  lowerCAmelCase__		(    self	:    List[str]  ,		snake_case_	:    Optional[int]=0 ):
							UpperCamelCase_:							str		=  floats_tensor((1, 3, 128, 128)  ,		rng=random.Random(snake_case_ ) )
							UpperCamelCase_:							Optional[int]		=  np.random.RandomState(snake_case_ )
							UpperCamelCase_:							Dict		=  {
							    """prompt""": """A painting of a squirrel eating a burger""",
							    """image""": image,
							    """generator""": generator,
							    """num_inference_steps""": 3,
							    """strength""": 0.75,
							    """guidance_scale""": 7.5,
							    """output_type""": """numpy""",
							}
							return inputs

			def  lowerCAmelCase__		(    self	:    Any ):
							UpperCamelCase_:							Any		=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint  ,		provider="""CPUExecutionProvider""" )
							pipe.set_progress_bar_config(disable=snake_case_ )

							UpperCamelCase_:							str		=  self.get_dummy_inputs()
							UpperCamelCase_:							Any		=  pipe(**snake_case_ ).images
							UpperCamelCase_:							Any		=  image[0, -3:, -3:, -1].flatten()

							assert image.shape == (1, 128, 128, 3)
							UpperCamelCase_:							str		=  np.array([0.6_9643, 0.5_8484, 0.5_0314, 0.5_8760, 0.5_5368, 0.5_9643, 0.5_1529, 0.4_1217, 0.4_9087] )
							assert np.abs(image_slice - expected_slice ).max() < 1e-1

			def  lowerCAmelCase__		(    self	:    List[str] ):
							UpperCamelCase_:							int		=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint  ,		provider="""CPUExecutionProvider""" )
							UpperCamelCase_:							Tuple		=  PNDMScheduler.from_config(pipe.scheduler.config  ,		skip_prk_steps=snake_case_ )
							pipe.set_progress_bar_config(disable=snake_case_ )

							UpperCamelCase_:							str		=  self.get_dummy_inputs()
							UpperCamelCase_:							Dict		=  pipe(**snake_case_ ).images
							UpperCamelCase_:							Optional[Any]		=  image[0, -3:, -3:, -1]

							assert image.shape == (1, 128, 128, 3)
							UpperCamelCase_:							Any		=  np.array([0.6_1737, 0.5_4642, 0.5_3183, 0.5_4465, 0.5_2742, 0.6_0525, 0.4_9969, 0.4_0655, 0.4_8154] )

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

			def  lowerCAmelCase__		(    self	:    str ):
							UpperCamelCase_:							str		=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint  ,		provider="""CPUExecutionProvider""" )
							UpperCamelCase_:							List[Any]		=  LMSDiscreteScheduler.from_config(pipe.scheduler.config )
							pipe.set_progress_bar_config(disable=snake_case_ )

							# warmup pass to apply optimizations
							UpperCamelCase_:							Union[str, Any]		=  pipe(**self.get_dummy_inputs() )

							UpperCamelCase_:							Tuple		=  self.get_dummy_inputs()
							UpperCamelCase_:							Optional[int]		=  pipe(**snake_case_ ).images
							UpperCamelCase_:							str		=  image[0, -3:, -3:, -1]

							assert image.shape == (1, 128, 128, 3)
							UpperCamelCase_:							Optional[int]		=  np.array([0.5_2761, 0.5_9977, 0.4_9033, 0.4_9619, 0.5_4282, 0.5_0311, 0.4_7600, 0.4_0918, 0.4_5203] )

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

			def  lowerCAmelCase__		(    self	:    Union[str, Any] ):
							UpperCamelCase_:							List[str]		=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint  ,		provider="""CPUExecutionProvider""" )
							UpperCamelCase_:							Optional[int]		=  EulerDiscreteScheduler.from_config(pipe.scheduler.config )
							pipe.set_progress_bar_config(disable=snake_case_ )

							UpperCamelCase_:							Union[str, Any]		=  self.get_dummy_inputs()
							UpperCamelCase_:							List[Any]		=  pipe(**snake_case_ ).images
							UpperCamelCase_:							List[Any]		=  image[0, -3:, -3:, -1]

							assert image.shape == (1, 128, 128, 3)
							UpperCamelCase_:							List[str]		=  np.array([0.5_2911, 0.6_0004, 0.4_9229, 0.4_9805, 0.5_4502, 0.5_0680, 0.4_7777, 0.4_1028, 0.4_5304] )

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

			def  lowerCAmelCase__		(    self	:    Optional[int] ):
							UpperCamelCase_:							List[Any]		=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint  ,		provider="""CPUExecutionProvider""" )
							UpperCamelCase_:							List[Any]		=  EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config )
							pipe.set_progress_bar_config(disable=snake_case_ )

							UpperCamelCase_:							List[str]		=  self.get_dummy_inputs()
							UpperCamelCase_:							Any		=  pipe(**snake_case_ ).images
							UpperCamelCase_:							Any		=  image[0, -3:, -3:, -1]

							assert image.shape == (1, 128, 128, 3)
							UpperCamelCase_:							Tuple		=  np.array([0.5_2911, 0.6_0004, 0.4_9229, 0.4_9805, 0.5_4502, 0.5_0680, 0.4_7777, 0.4_1028, 0.4_5304] )

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




			def  lowerCAmelCase__		(    self	:    Union[str, Any] ):
							UpperCamelCase_:							Optional[Any]		=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint  ,		provider="""CPUExecutionProvider""" )
							UpperCamelCase_:							str		=  DPMSolverMultistepScheduler.from_config(pipe.scheduler.config )
							pipe.set_progress_bar_config(disable=snake_case_ )

							UpperCamelCase_:							List[Any]		=  self.get_dummy_inputs()
							UpperCamelCase_:							Optional[int]		=  pipe(**snake_case_ ).images
							UpperCamelCase_:							Dict		=  image[0, -3:, -3:, -1]

							assert image.shape == (1, 128, 128, 3)
							UpperCamelCase_:							Tuple		=  np.array([0.6_5331, 0.5_8277, 0.4_8204, 0.5_6059, 0.5_3665, 0.5_6235, 0.5_0969, 0.4_0009, 0.4_6552] )

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




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






			'''simple docstring'''

			@property
			def  lowerCAmelCase__		(    self	:    int ):
							return (
							    "CUDAExecutionProvider",
							    {
							        "gpu_mem_limit": "15000000000",  # 15GB
							        "arena_extend_strategy": "kSameAsRequested",
							    },
							)

			@property
			def  lowerCAmelCase__		(    self	:    List[Any] ):
							UpperCamelCase_:							Dict		=  ort.SessionOptions()
							UpperCamelCase_:							Optional[int]		=  False
							return options

			def  lowerCAmelCase__		(    self	:    Tuple ):
							UpperCamelCase_:							Optional[int]		=  load_image(
							    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
							    """/img2img/sketch-mountains-input.jpg""" )
							UpperCamelCase_:							Union[str, Any]		=  init_image.resize((768, 512) )
							# using the PNDM scheduler by default
							UpperCamelCase_:							int		=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(
							    """CompVis/stable-diffusion-v1-4"""  ,		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_ )

							UpperCamelCase_:							Dict		=  """A fantasy landscape, trending on artstation"""

							UpperCamelCase_:							List[str]		=  np.random.RandomState(0 )
							UpperCamelCase_:							List[str]		=  pipe(
							    prompt=snake_case_  ,		image=snake_case_  ,		strength=0.75  ,		guidance_scale=7.5  ,		num_inference_steps=10  ,		generator=snake_case_  ,		output_type="""np"""  ,		)
							UpperCamelCase_:							List[str]		=  output.images
							UpperCamelCase_:							Optional[Any]		=  images[0, 255:258, 383:386, -1]

							assert images.shape == (1, 512, 768, 3)
							UpperCamelCase_:							Tuple		=  np.array([0.4909, 0.5059, 0.5372, 0.4623, 0.4876, 0.5049, 0.4820, 0.4956, 0.5019] )
							# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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




			def  lowerCAmelCase__		(    self	:    Optional[Any] ):
							UpperCamelCase_:							Union[str, Any]		=  load_image(
							    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
							    """/img2img/sketch-mountains-input.jpg""" )
							UpperCamelCase_:							List[Any]		=  init_image.resize((768, 512) )
							UpperCamelCase_:							Union[str, Any]		=  LMSDiscreteScheduler.from_pretrained(
							    """runwayml/stable-diffusion-v1-5"""  ,		subfolder="""scheduler"""  ,		revision="""onnx""" )
							UpperCamelCase_:							Dict		=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(
							    """runwayml/stable-diffusion-v1-5"""  ,		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_ )

							UpperCamelCase_:							Any		=  """A fantasy landscape, trending on artstation"""

							UpperCamelCase_:							Dict		=  np.random.RandomState(0 )
							UpperCamelCase_:							Union[str, Any]		=  pipe(
							    prompt=snake_case_  ,		image=snake_case_  ,		strength=0.75  ,		guidance_scale=7.5  ,		num_inference_steps=20  ,		generator=snake_case_  ,		output_type="""np"""  ,		)
							UpperCamelCase_:							Optional[int]		=  output.images
							UpperCamelCase_:							Dict		=  images[0, 255:258, 383:386, -1]

							assert images.shape == (1, 512, 768, 3)
							UpperCamelCase_:							Optional[int]		=  np.array([0.8043, 0.926, 0.9581, 0.8119, 0.8954, 0.913, 0.7209, 0.7463, 0.7431] )
							# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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






