




"""simple docstring"""




import gc
import random
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, CycleDiffusionPipeline, DDIMScheduler, UNetaDConditionModel
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()

class    UpperCAmelCase_  (       _a					, _a					, unittest.TestCase						):
		UpperCamelCase						 =CycleDiffusionPipeline
		UpperCamelCase						 =TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {
		    """negative_prompt""",
		    """height""",
		    """width""",
		    """negative_prompt_embeds""",
		}
		UpperCamelCase						 =PipelineTesterMixin.required_optional_params - {"""latents"""}
		UpperCamelCase						 =TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"source_prompt"}						)
		UpperCamelCase						 =IMAGE_TO_IMAGE_IMAGE_PARAMS
		UpperCamelCase						 =IMAGE_TO_IMAGE_IMAGE_PARAMS
		def      _lowerCamelCase				(		self    )		->    List[str]:
					torch.manual_seed(0    )
					__lowercase       :   Optional[int]        =    UNetaDConditionModel(
					    block_out_channels=(32, 64)							,		layers_per_block=2							,		sample_size=32							,		in_channels=4							,		out_channels=4							,		down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')							,		up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')							,		cross_attention_dim=32							,		)
					__lowercase       :   Union[str, Any]        =    DDIMScheduler(
					    beta_start=0.0_0_0_8_5							,		beta_end=0.0_1_2							,		beta_schedule='''scaled_linear'''							,		num_train_timesteps=10_00							,		clip_sample=__lowerCamelCase							,		set_alpha_to_one=__lowerCamelCase							,		)
					torch.manual_seed(0    )
					__lowercase       :   Dict        =    AutoencoderKL(
					    block_out_channels=[32, 64]							,		in_channels=3							,		out_channels=3							,		down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']							,		up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']							,		latent_channels=4							,		)
					torch.manual_seed(0    )
					__lowercase       :   List[Any]        =    CLIPTextConfig(
					    bos_token_id=0							,		eos_token_id=2							,		hidden_size=32							,		intermediate_size=37							,		layer_norm_eps=1E-05							,		num_attention_heads=4							,		num_hidden_layers=5							,		pad_token_id=1							,		vocab_size=10_00							,		)
					__lowercase       :   List[Any]        =    CLIPTextModel(__lowerCamelCase    )
					__lowercase       :   Optional[int]        =    CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''    )

					__lowercase       :   List[str]        =    {
					    """unet""": unet,
					    """scheduler""": scheduler,
					    """vae""": vae,
					    """text_encoder""": text_encoder,
					    """tokenizer""": tokenizer,
					    """safety_checker""": None,
					    """feature_extractor""": None,
					}
					return components
		def      _lowerCamelCase				(		self							,		UpperCamelCase_							,		UpperCamelCase_=0    )		->    Optional[int]:
					__lowercase       :   Union[str, Any]        =    floats_tensor((1, 3, 32, 32)							,		rng=random.Random(__lowerCamelCase    )    ).to(__lowerCamelCase    )
					__lowercase       :   List[str]        =    image / 2 + 0.5
					if str(__lowerCamelCase    ).startswith('''mps'''    ):
								__lowercase       :   Union[str, Any]        =    torch.manual_seed(__lowerCamelCase    )
					else:
								__lowercase       :   List[Any]        =    torch.Generator(device=__lowerCamelCase    ).manual_seed(__lowerCamelCase    )
					__lowercase       :   Optional[Any]        =    {
					    """prompt""": """An astronaut riding an elephant""",
					    """source_prompt""": """An astronaut riding a horse""",
					    """image""": image,
					    """generator""": generator,
					    """num_inference_steps""": 2,
					    """eta""": 0.1,
					    """strength""": 0.8,
					    """guidance_scale""": 3,
					    """source_guidance_scale""": 1,
					    """output_type""": """numpy""",
					}
					return inputs
		def      _lowerCamelCase				(		self    )		->    Dict:
					__lowercase       :   Dict        =    """cpu"""  # ensure determinism for the device-dependent torch.Generator

					__lowercase       :   str        =    self.get_dummy_components()
					__lowercase       :   int        =    CycleDiffusionPipeline(**__lowerCamelCase    )
					__lowercase       :   Dict        =    pipe.to(__lowerCamelCase    )
					pipe.set_progress_bar_config(disable=__lowerCamelCase    )

					__lowercase       :   Tuple        =    self.get_dummy_inputs(__lowerCamelCase    )
					__lowercase       :   Any        =    pipe(**__lowerCamelCase    )
					__lowercase       :   Dict        =    output.images

					__lowercase       :   Any        =    images[0, -3:, -3:, -1]

					assert images.shape == (1, 32, 32, 3)
					__lowercase       :   int        =    np.array([0.4_4_5_9, 0.4_9_4_3, 0.4_5_4_4, 0.6_6_4_3, 0.5_4_7_4, 0.4_3_2_7, 0.5_7_0_1, 0.5_9_5_9, 0.5_1_7_9]    )

					assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1E-2
		@unittest.skipIf(torch_device != '''cuda'''							,		'''This test requires a GPU'''    )
		def      _lowerCamelCase				(		self    )		->    Optional[int]:
					__lowercase       :   Dict        =    self.get_dummy_components()
					for name, module in components.items():
								if hasattr(__lowerCamelCase							,		'''half'''    ):
											__lowercase       :   Optional[Any]        =    module.half()
					__lowercase       :   int        =    CycleDiffusionPipeline(**__lowerCamelCase    )
					__lowercase       :   Optional[Any]        =    pipe.to(__lowerCamelCase    )
					pipe.set_progress_bar_config(disable=__lowerCamelCase    )

					__lowercase       :   Any        =    self.get_dummy_inputs(__lowerCamelCase    )
					__lowercase       :   Optional[int]        =    pipe(**__lowerCamelCase    )
					__lowercase       :   List[str]        =    output.images

					__lowercase       :   Optional[Any]        =    images[0, -3:, -3:, -1]

					assert images.shape == (1, 32, 32, 3)
					__lowercase       :   List[str]        =    np.array([0.3_5_0_6, 0.4_5_4_3, 0.4_4_6, 0.4_5_7_5, 0.5_1_9_5, 0.4_1_5_5, 0.5_2_7_3, 0.5_1_8, 0.4_1_1_6]    )

					assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1E-2
		@skip_mps
		def      _lowerCamelCase				(		self    )		->    Any:
					return super().test_save_load_local()
		@unittest.skip('''non-deterministic pipeline'''    )
		def      _lowerCamelCase				(		self    )		->    List[str]:
					return super().test_inference_batch_single_identical()
		@skip_mps
		def      _lowerCamelCase				(		self    )		->    Tuple:
					return super().test_dict_tuple_outputs_equivalent()
		@skip_mps
		def      _lowerCamelCase				(		self    )		->    Dict:
					return super().test_save_load_optional_components()
		@skip_mps
		def      _lowerCamelCase				(		self    )		->    Any:
					return super().test_attention_slicing_forward_pass()


@slow
@require_torch_gpu
class    UpperCAmelCase_  (       unittest.TestCase						):
		def      _lowerCamelCase				(		self    )		->    Dict:
					# clean up the VRAM after each test
					super().tearDown()
					gc.collect()
					torch.cuda.empty_cache()
		def      _lowerCamelCase				(		self    )		->    List[str]:
					__lowercase       :   int        =    load_image(
					    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
					    '''/cycle-diffusion/black_colored_car.png'''    )
					__lowercase       :   List[Any]        =    load_numpy(
					    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car_fp16.npy'''    )
					__lowercase       :   Any        =    init_image.resize((5_12, 5_12)    )

					__lowercase       :   Dict        =    """CompVis/stable-diffusion-v1-4"""
					__lowercase       :   List[Any]        =    DDIMScheduler.from_pretrained(__lowerCamelCase							,		subfolder='''scheduler'''    )
					__lowercase       :   str        =    CycleDiffusionPipeline.from_pretrained(
					    __lowerCamelCase							,		scheduler=__lowerCamelCase							,		safety_checker=__lowerCamelCase							,		torch_dtype=torch.floataa							,		revision='''fp16'''    )

					pipe.to(__lowerCamelCase    )
					pipe.set_progress_bar_config(disable=__lowerCamelCase    )
					pipe.enable_attention_slicing()

					__lowercase       :   List[Any]        =    """A black colored car"""
					__lowercase       :   Tuple        =    """A blue colored car"""

					__lowercase       :   Tuple        =    torch.manual_seed(0    )
					__lowercase       :   List[Any]        =    pipe(
					    prompt=__lowerCamelCase							,		source_prompt=__lowerCamelCase							,		image=__lowerCamelCase							,		num_inference_steps=1_00							,		eta=0.1							,		strength=0.8_5							,		guidance_scale=3							,		source_guidance_scale=1							,		generator=__lowerCamelCase							,		output_type='''np'''							,		)
					__lowercase       :   Optional[int]        =    output.images

					# the values aren't exactly equal, but the images look the same visually
					assert np.abs(image - expected_image    ).max() < 5E-1
		def      _lowerCamelCase				(		self    )		->    Union[str, Any]:
					__lowercase       :   Dict        =    load_image(
					    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
					    '''/cycle-diffusion/black_colored_car.png'''    )
					__lowercase       :   Any        =    load_numpy(
					    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car.npy'''    )
					__lowercase       :   Optional[Any]        =    init_image.resize((5_12, 5_12)    )

					__lowercase       :   str        =    """CompVis/stable-diffusion-v1-4"""
					__lowercase       :   Union[str, Any]        =    DDIMScheduler.from_pretrained(__lowerCamelCase							,		subfolder='''scheduler'''    )
					__lowercase       :   str        =    CycleDiffusionPipeline.from_pretrained(__lowerCamelCase							,		scheduler=__lowerCamelCase							,		safety_checker=__lowerCamelCase    )

					pipe.to(__lowerCamelCase    )
					pipe.set_progress_bar_config(disable=__lowerCamelCase    )
					pipe.enable_attention_slicing()

					__lowercase       :   Dict        =    """A black colored car"""
					__lowercase       :   str        =    """A blue colored car"""

					__lowercase       :   List[Any]        =    torch.manual_seed(0    )
					__lowercase       :   Optional[int]        =    pipe(
					    prompt=__lowerCamelCase							,		source_prompt=__lowerCamelCase							,		image=__lowerCamelCase							,		num_inference_steps=1_00							,		eta=0.1							,		strength=0.8_5							,		guidance_scale=3							,		source_guidance_scale=1							,		generator=__lowerCamelCase							,		output_type='''np'''							,		)
					__lowercase       :   Optional[int]        =    output.images

					assert np.abs(image - expected_image    ).max() < 2E-2











# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ..models.whisper import WhisperForConditionalGeneration, WhisperProcessor
from .base import PipelineTool

class     _SCREAMING_SNAKE_CASE       (			_a      ):
	snake_case__							:     Any     	=  """openai/whisper-base"""
	snake_case__							:     Optional[int]     	=  (
	    """This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the """
	    """transcribed text."""
	)
	snake_case__							:     Any     	=  """transcriber"""
	snake_case__							:     Optional[int]     	=  WhisperProcessor
	snake_case__							:     str     	=  WhisperForConditionalGeneration

	snake_case__							:     Optional[Any]     	=  ["""audio"""]
	snake_case__							:     Any     	=  ["""text"""]





	def 						_A (		self				:					str ,  __lowerCamelCase				:					Dict	):
		return self.pre_processor(__lowerCamelCase ,  return_tensors="""pt"""	).input_features





	def 						_A (		self				:					Dict ,  __lowerCamelCase				:					List[Any]	):
		return self.model.generate(inputs=__lowerCamelCase	)





	def 						_A (		self				:					Any ,  __lowerCamelCase				:					Optional[Any]	):
		return self.pre_processor.batch_decode(__lowerCamelCase ,  skip_special_tokens=__lowerCamelCase	)[0]
