




"""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  lowercase(					__a	,      __a	,      unittest.TestCase			):







 '''simple docstring'''





 lowercase__			 = CycleDiffusionPipeline
 lowercase__			 = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {
     "negative_prompt",
     "height",
     "width",
     "negative_prompt_embeds",
 }
 lowercase__			 = PipelineTesterMixin.required_optional_params - {"latents"}
 lowercase__			 = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"source_prompt"}			)
 lowercase__			 = IMAGE_TO_IMAGE_IMAGE_PARAMS
 lowercase__			 = IMAGE_TO_IMAGE_IMAGE_PARAMS


 def 			UpperCamelCase_       (    self:		int		):




   '''simple docstring'''



   torch.manual_seed(0		)
   _snake_case							:		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,				)
   _snake_case							:		Tuple								=  DDIMScheduler(
       beta_start=0.00_085,				beta_end=0.012,				beta_schedule="""scaled_linear""",				num_train_timesteps=1_000,				clip_sample=a_,				set_alpha_to_one=a_,				)
   torch.manual_seed(0		)
   _snake_case							:		Optional[int]								=  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		)
   _snake_case							:		Optional[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=1_000,				)
   _snake_case							:		Optional[Any]								=  CLIPTextModel(a_		)
   _snake_case							:		List[Any]								=  CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""		)

   _snake_case							:		Tuple								=  {
       """unet""": unet,
       """scheduler""": scheduler,
       """vae""": vae,
       """text_encoder""": text_encoder,
       """tokenizer""": tokenizer,
       """safety_checker""": None,
       """feature_extractor""": None,
   }
   return components


 def 			UpperCamelCase_       (    self:		int,				a_:		List[Any],				a_:		List[Any]=0		):




   '''simple docstring'''



   _snake_case							:		Union[str, Any]								=  floats_tensor((1, 3, 32, 32),				rng=random.Random(a_		)		).to(a_		)
   _snake_case							:		Any								=  image / 2 + 0.5
   if str(a_		).startswith("""mps"""		):
     _snake_case							:		int								=  torch.manual_seed(a_		)
   else:
     _snake_case							:		Dict								=  torch.Generator(device=a_		).manual_seed(a_		)
   _snake_case							:		Dict								=  {
       """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 			UpperCamelCase_       (    self:		Optional[Any]		):




   '''simple docstring'''



   _snake_case							:		Any								=  """cpu"""  # ensure determinism for the device-dependent torch.Generator

   _snake_case							:		List[str]								=  self.get_dummy_components()
   _snake_case							:		List[str]								=  CycleDiffusionPipeline(**a_		)
   _snake_case							:		Union[str, Any]								=  pipe.to(a_		)
   pipe.set_progress_bar_config(disable=a_		)

   _snake_case							:		Union[str, Any]								=  self.get_dummy_inputs(a_		)
   _snake_case							:		Optional[int]								=  pipe(**a_		)
   _snake_case							:		Any								=  output.images

   _snake_case							:		int								=  images[0, -3:, -3:, -1]

   assert images.shape == (1, 32, 32, 3)
   _snake_case							:		Optional[int]								=  np.array([0.4_459, 0.4_943, 0.4_544, 0.6_643, 0.5_474, 0.4_327, 0.5_701, 0.5_959, 0.5_179]		)

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


 @unittest.skipIf(torch_device != """cuda""",				"""This test requires a GPU"""		)
 def 			UpperCamelCase_       (    self:		Tuple		):




   '''simple docstring'''



   _snake_case							:		Optional[Any]								=  self.get_dummy_components()
   for name, module in components.items():
     if hasattr(a_,				"""half"""		):
       _snake_case							:		List[Any]								=  module.half()
   _snake_case							:		int								=  CycleDiffusionPipeline(**a_		)
   _snake_case							:		Any								=  pipe.to(a_		)
   pipe.set_progress_bar_config(disable=a_		)

   _snake_case							:		Any								=  self.get_dummy_inputs(a_		)
   _snake_case							:		Optional[int]								=  pipe(**a_		)
   _snake_case							:		Union[str, Any]								=  output.images

   _snake_case							:		Optional[int]								=  images[0, -3:, -3:, -1]

   assert images.shape == (1, 32, 32, 3)
   _snake_case							:		Optional[int]								=  np.array([0.3_506, 0.4_543, 0.446, 0.4_575, 0.5_195, 0.4_155, 0.5_273, 0.518, 0.4_116]		)

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


 @skip_mps
 def 			UpperCamelCase_       (    self:		Union[str, Any]		):




   '''simple docstring'''



   return super().test_save_load_local()


 @unittest.skip("""non-deterministic pipeline"""		)
 def 			UpperCamelCase_       (    self:		Union[str, Any]		):




   '''simple docstring'''



   return super().test_inference_batch_single_identical()


 @skip_mps
 def 			UpperCamelCase_       (    self:		Tuple		):




   '''simple docstring'''



   return super().test_dict_tuple_outputs_equivalent()


 @skip_mps
 def 			UpperCamelCase_       (    self:		List[Any]		):




   '''simple docstring'''



   return super().test_save_load_optional_components()


 @skip_mps
 def 			UpperCamelCase_       (    self:		Optional[int]		):




   '''simple docstring'''



   return super().test_attention_slicing_forward_pass()







@slow
@require_torch_gpu
class  lowercase(					unittest.TestCase			):







 '''simple docstring'''





 def 			UpperCamelCase_       (    self:		str		):




   '''simple docstring'''



   super().tearDown()
   gc.collect()
   torch.cuda.empty_cache()


 def 			UpperCamelCase_       (    self:		Optional[Any]		):




   '''simple docstring'''



   _snake_case							:		Any								=  load_image(
       """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
       """/cycle-diffusion/black_colored_car.png"""		)
   _snake_case							:		List[Any]								=  load_numpy(
       """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car_fp16.npy"""		)
   _snake_case							:		Optional[int]								=  init_image.resize((512, 512)		)

   _snake_case							:		Union[str, Any]								=  """CompVis/stable-diffusion-v1-4"""
   _snake_case							:		str								=  DDIMScheduler.from_pretrained(a_,				subfolder="""scheduler"""		)
   _snake_case							:		Optional[int]								=  CycleDiffusionPipeline.from_pretrained(
       a_,				scheduler=a_,				safety_checker=a_,				torch_dtype=torch.floataa,				revision="""fp16"""		)

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

   _snake_case							:		Optional[Any]								=  """A black colored car"""
   _snake_case							:		int								=  """A blue colored car"""

   _snake_case							:		Any								=  torch.manual_seed(0		)
   _snake_case							:		Dict								=  pipe(
       prompt=a_,				source_prompt=a_,				image=a_,				num_inference_steps=100,				eta=0.1,				strength=0.85,				guidance_scale=3,				source_guidance_scale=1,				generator=a_,				output_type="""np""",				)
   _snake_case							:		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 			UpperCamelCase_       (    self:		Optional[int]		):




   '''simple docstring'''



   _snake_case							:		List[Any]								=  load_image(
       """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
       """/cycle-diffusion/black_colored_car.png"""		)
   _snake_case							:		Tuple								=  load_numpy(
       """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car.npy"""		)
   _snake_case							:		Dict								=  init_image.resize((512, 512)		)

   _snake_case							:		Optional[Any]								=  """CompVis/stable-diffusion-v1-4"""
   _snake_case							:		Optional[Any]								=  DDIMScheduler.from_pretrained(a_,				subfolder="""scheduler"""		)
   _snake_case							:		Optional[int]								=  CycleDiffusionPipeline.from_pretrained(a_,				scheduler=a_,				safety_checker=a_		)

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

   _snake_case							:		Tuple								=  """A black colored car"""
   _snake_case							:		int								=  """A blue colored car"""

   _snake_case							:		Tuple								=  torch.manual_seed(0		)
   _snake_case							:		List[str]								=  pipe(
       prompt=a_,				source_prompt=a_,				image=a_,				num_inference_steps=100,				eta=0.1,				strength=0.85,				guidance_scale=3,				source_guidance_scale=1,				generator=a_,				output_type="""np""",				)
   _snake_case							:		List[str]								=  output.images

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








"""simple docstring"""


import unicodedata
from dataclasses import dataclass
from typing import Optional, Union

import numpy as np

from transformers.data.data_collator import DataCollatorMixin
from transformers.file_utils import PaddingStrategy
from transformers.tokenization_utils_base import PreTrainedTokenizerBase


def  UpperCAmelCase__	(snake_case__							: Optional[int]		,       snake_case__							: Any		,       snake_case__							: List[str]		,       snake_case__							: int   ):
  """simple docstring"""

  if isinstance(snake_case__		,       snake_case__   ):
    _snake_case							:		List[Any]								=  np.full((len(snake_case__   ), sequence_length, 2)		,       snake_case__   )
  else:
    _snake_case							:		Any								=  np.full((len(snake_case__   ), sequence_length)		,       snake_case__   )

  for i, tensor in enumerate(snake_case__   ):
    if padding_side == "right":
      if isinstance(snake_case__		,       snake_case__   ):
        _snake_case							:		Dict								=  tensor[:sequence_length]
      else:
        _snake_case							:		List[Any]								=  tensor[:sequence_length]
    else:
      if isinstance(snake_case__		,       snake_case__   ):
        _snake_case							:		str								=  tensor[:sequence_length]
      else:
        _snake_case							:		Tuple								=  tensor[:sequence_length]

  return out_tensor.tolist()


def  UpperCAmelCase__	(snake_case__							: Optional[int]   ):
  """simple docstring"""

  _snake_case							:		str								=  ord(snake_case__   )
  if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 1_23 and cp <= 1_26):
    return True
  _snake_case							:		Union[str, Any]								=  unicodedata.category(snake_case__   )
  if cat.startswith("""P"""   ):
    return True
  return False






@dataclass
class  lowercase(					__a			):







 '''simple docstring'''





 lowercase__			 = 42
 lowercase__			 = True
 lowercase__			 = None
 lowercase__			 = None
 lowercase__			 = -1_00
 lowercase__			 = "pt"


 def 			UpperCamelCase_       (    self:		Any,				a_:		Union[str, Any]		):




   '''simple docstring'''



   import torch

   _snake_case							:		Optional[Any]								=  """label""" if """label""" in features[0].keys() else """labels"""
   _snake_case							:		str								=  [feature[label_name] for feature in features] if label_name in features[0].keys() else None
   _snake_case							:		Any								=  self.tokenizer.pad(
       a_,				padding=self.padding,				max_length=self.max_length,				pad_to_multiple_of=self.pad_to_multiple_of,				return_tensors="""pt""" if labels is None else None,				)

   if labels is None:
     return batch

   _snake_case							:		Optional[int]								=  torch.tensor(batch["""entity_ids"""]		).shape[1]
   _snake_case							:		Any								=  self.tokenizer.padding_side
   if padding_side == "right":
     _snake_case							:		Optional[int]								=  [
         list(a_		) + [self.label_pad_token_id] * (sequence_length - len(a_		)) for label in labels
     ]
   else:
     _snake_case							:		Union[str, Any]								=  [
         [self.label_pad_token_id] * (sequence_length - len(a_		)) + list(a_		) for label in labels
     ]

   _snake_case							:		List[Any]								=  [feature["""ner_tags"""] for feature in features]
   _snake_case							:		str								=  padding_tensor(a_,				-1,				a_,				a_		)
   _snake_case							:		Any								=  [feature["""original_entity_spans"""] for feature in features]
   _snake_case							:		int								=  padding_tensor(a_,				(-1, -1),				a_,				a_		)
   _snake_case							:		str								=  {k: torch.tensor(a_,				dtype=torch.intaa		) for k, v in batch.items()}

   return batch


