

import subprocess
import sys

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


class        _SCREAMING_SNAKE_CASE	(   a__):







						@require_torch
						def     _snake_case							(       self				)->				str:
													# 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
													lowerCamelCase_				     ="\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n        "

													lowerCamelCase_				     ="\nmname = \"hf-internal-testing/tiny-random-bert\"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task=\"fill-mask\", model=mname)\nprint(\"success\")\n        "

													lowerCamelCase_				     ="\nimport socket\ndef offline_socket(*args, **kwargs): raise RuntimeError(\"Offline mode is enabled, we shouldn't access internet\")\nsocket.socket = offline_socket\n        "

													# Force fetching the files so that we can use the cache
													lowerCamelCase_				     ="hf-internal-testing/tiny-random-bert"
													BertConfig.from_pretrained(lowerCAmelCase__				)
													BertModel.from_pretrained(lowerCAmelCase__				)
													BertTokenizer.from_pretrained(lowerCAmelCase__				)
													pipeline(task="""fill-mask"""			,		model=lowerCAmelCase__				)

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

													# should succeed
													lowerCamelCase_				     =self.get_env()
													# should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
													lowerCamelCase_				     ="1"
													lowerCamelCase_				     =subprocess.run(lowerCAmelCase__			,		env=lowerCAmelCase__			,		check=lowerCAmelCase__			,		capture_output=lowerCAmelCase__				)
													self.assertEqual(result.returncode			,		0			,		result.stderr				)
													self.assertIn("""success"""			,		result.stdout.decode()				)







						@require_torch
						def     _snake_case							(       self				)->				Optional[Any]:
													# python one-liner segments
													# this must be loaded before socket.socket is monkey-patched
													lowerCamelCase_				     ="\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n        "

													lowerCamelCase_				     ="\nmname = \"hf-internal-testing/tiny-random-bert\"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task=\"fill-mask\", model=mname)\nprint(\"success\")\n        "

													lowerCamelCase_				     ="\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error(\"Faking flaky internet\")\nsocket.socket = offline_socket\n        "

													# Force fetching the files so that we can use the cache
													lowerCamelCase_				     ="hf-internal-testing/tiny-random-bert"
													BertConfig.from_pretrained(lowerCAmelCase__				)
													BertModel.from_pretrained(lowerCAmelCase__				)
													BertTokenizer.from_pretrained(lowerCAmelCase__				)
													pipeline(task="""fill-mask"""			,		model=lowerCAmelCase__				)

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

													# should succeed
													lowerCamelCase_				     =self.get_env()
													lowerCamelCase_				     =subprocess.run(lowerCAmelCase__			,		env=lowerCAmelCase__			,		check=lowerCAmelCase__			,		capture_output=lowerCAmelCase__				)
													self.assertEqual(result.returncode			,		0			,		result.stderr				)
													self.assertIn("""success"""			,		result.stdout.decode()				)







						@require_torch
						def     _snake_case							(       self				)->				Tuple:
													# 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
													lowerCamelCase_				     ="\nfrom transformers import BertConfig, BertModel, BertTokenizer\n        "

													lowerCamelCase_				     ="\nmname = \"hf-internal-testing/tiny-random-bert-sharded\"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nprint(\"success\")\n        "

													lowerCamelCase_				     ="\nimport socket\ndef offline_socket(*args, **kwargs): raise ValueError(\"Offline mode is enabled\")\nsocket.socket = offline_socket\n        "

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

													# should succeed
													lowerCamelCase_				     =self.get_env()
													lowerCamelCase_				     =subprocess.run(lowerCAmelCase__			,		env=lowerCAmelCase__			,		check=lowerCAmelCase__			,		capture_output=lowerCAmelCase__				)
													self.assertEqual(result.returncode			,		0			,		result.stderr				)
													self.assertIn("""success"""			,		result.stdout.decode()				)

													# next emulate no network
													lowerCamelCase_				     =[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
													lowerCamelCase_				     ="1"
													lowerCamelCase_				     =subprocess.run(lowerCAmelCase__			,		env=lowerCAmelCase__			,		check=lowerCAmelCase__			,		capture_output=lowerCAmelCase__				)
													self.assertEqual(result.returncode			,		0			,		result.stderr				)
													self.assertIn("""success"""			,		result.stdout.decode()				)







						@require_torch
						def     _snake_case							(       self				)->				Optional[Any]:
													lowerCamelCase_				     ="\nfrom transformers import pipeline\n        "
													lowerCamelCase_				     ="\nmname = \"hf-internal-testing/tiny-random-bert\"\npipe = pipeline(model=mname)\n        "

													lowerCamelCase_				     ="\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error(\"Offline mode is enabled\")\nsocket.socket = offline_socket\n        "
													lowerCamelCase_				     =self.get_env()
													lowerCamelCase_				     ="1"
													lowerCamelCase_				     =[sys.executable, "-c", "\n".join([load, mock, run]				)]
													lowerCamelCase_				     =subprocess.run(lowerCAmelCase__			,		env=lowerCAmelCase__			,		check=lowerCAmelCase__			,		capture_output=lowerCAmelCase__				)
													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     _snake_case							(       self				)->				Tuple:
													lowerCamelCase_				     ="\nfrom transformers import AutoModel\n        "
													lowerCamelCase_				     ="\nmname = \"hf-internal-testing/test_dynamic_model\"\nAutoModel.from_pretrained(mname, trust_remote_code=True)\nprint(\"success\")\n        "

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

													# should succeed
													lowerCamelCase_				     =self.get_env()
													lowerCamelCase_				     =subprocess.run(lowerCAmelCase__			,		env=lowerCAmelCase__			,		check=lowerCAmelCase__			,		capture_output=lowerCAmelCase__				)
													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
													lowerCamelCase_				     ="1"
													lowerCamelCase_				     =subprocess.run(lowerCAmelCase__			,		env=lowerCAmelCase__			,		check=lowerCAmelCase__			,		capture_output=lowerCAmelCase__				)
													self.assertEqual(result.returncode			,		0			,		result.stderr				)
													self.assertIn("""success"""			,		result.stdout.decode()				)







"""simple docstring"""




import inspect
from typing import List, Optional, Tuple, Union

import numpy as np
import PIL
import torch
import torch.utils.checkpoint

from ...models import UNetaDModel, VQModel
from ...schedulers import (
    DDIMScheduler,
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
)
from ...utils import PIL_INTERPOLATION, randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput






def       _SCREAMING_SNAKE_CASE		(	_lowercase						:    Union[str, Any]					) ->str:






	'''simple docstring'''






	a,       a      :		str	=				image.size
	a,       a      :		Tuple	=				(x - x % 32 for x in (w, h))  # resize to integer multiple of 32
	a      :		Union[str, Any]	=				image.resize((w, h)    ,       resample=PIL_INTERPOLATION["lanczos"]					)
	a      :		int	=				np.array(_lowercase					).astype(np.floataa					) / 255.0
	a      :		List[str]	=				image[None].transpose(0    ,       3    ,       1    ,       2					)
	a      :		Dict	=				torch.from_numpy(_lowercase					)
	return 2.0 * image - 1.0







class        __UpperCamelCase				(						a__						):






							def __init__(   self      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ,					)	-> str:
								super().__init__()
								self.register_modules(vqvae=lowerCAmelCase__      ,					unet=lowerCAmelCase__      ,					scheduler=lowerCAmelCase__      )






							@torch.no_grad()
							def __call__(   self      ,					lowerCAmelCase__ = None      ,					lowerCAmelCase__ = 1      ,					lowerCAmelCase__ = 100      ,					lowerCAmelCase__ = 0.0      ,					lowerCAmelCase__ = None      ,					lowerCAmelCase__ = "pil"      ,					lowerCAmelCase__ = True      ,					)	-> Union[Tuple, ImagePipelineOutput]:
								if isinstance(lowerCAmelCase__      ,					PIL.Image.Image      ):
									a      :		int	=				1
								elif isinstance(lowerCAmelCase__      ,					torch.Tensor      ):
									a      :		str	=				image.shape[0]
								else:
									raise ValueError(f"""`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(lowerCAmelCase__      )}"""      )

								if isinstance(lowerCAmelCase__      ,					PIL.Image.Image      ):
									a      :		Tuple	=				preprocess(lowerCAmelCase__      )

								a,       a      :		Optional[Any]	=				image.shape[-2:]

								# in_channels should be 6: 3 for latents, 3 for low resolution image
								a      :		Tuple	=				(batch_size, self.unet.config.in_channels // 2, height, width)
								a      :		List[str]	=				next(self.unet.parameters()      ).dtype

								a      :		Any	=				randn_tensor(lowerCAmelCase__      ,					generator=lowerCAmelCase__      ,					device=self.device      ,					dtype=lowerCAmelCase__      )

								a      :		Union[str, Any]	=				image.to(device=self.device      ,					dtype=lowerCAmelCase__      )

								# set timesteps and move to the correct device
								self.scheduler.set_timesteps(lowerCAmelCase__      ,					device=self.device      )
								a      :		int	=				self.scheduler.timesteps

								# scale the initial noise by the standard deviation required by the scheduler
								a      :		str	=				latents * self.scheduler.init_noise_sigma

								# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature.
								# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
								# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
								# and should be between [0, 1]
								a      :		str	=				"eta" in set(inspect.signature(self.scheduler.step      ).parameters.keys()      )
								a      :		List[Any]	=				{}
								if accepts_eta:
									a      :		Any	=				eta

								for t in self.progress_bar(lowerCAmelCase__      ):
									# concat latents and low resolution image in the channel dimension.
									a      :		str	=				torch.cat([latents, image]      ,					dim=1      )
									a      :		int	=				self.scheduler.scale_model_input(lowerCAmelCase__      ,					lowerCAmelCase__      )
									# predict the noise residual
									a      :		Union[str, Any]	=				self.unet(lowerCAmelCase__      ,					lowerCAmelCase__      ).sample
									# compute the previous noisy sample x_t -> x_t-1
									a      :		Tuple	=				self.scheduler.step(lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ,					**lowerCAmelCase__      ).prev_sample

								# decode the image latents with the VQVAE
								a      :		List[Any]	=				self.vqvae.decode(lowerCAmelCase__      ).sample
								a      :		int	=				torch.clamp(lowerCAmelCase__      ,					-1.0      ,					1.0      )
								a      :		Optional[int]	=				image / 2 + 0.5
								a      :		Optional[int]	=				image.cpu().permute(0      ,					2      ,					3      ,					1      ).numpy()

								if output_type == "pil":
									a      :		Union[str, Any]	=				self.numpy_to_pil(lowerCAmelCase__      )

								if not return_dict:
									return (image,)

								return ImagePipelineOutput(images=lowerCAmelCase__      )


