
'''simple docstring'''


import gc
import random
import unittest

import torch

from diffusers import (
    IFImgaImgPipeline,
    IFImgaImgSuperResolutionPipeline,
    IFInpaintingPipeline,
    IFInpaintingSuperResolutionPipeline,
    IFPipeline,
    IFSuperResolutionPipeline,
)
from diffusers.models.attention_processor import AttnAddedKVProcessor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
from . import IFPipelineTesterMixin


@skip_mps
class 						lowercase__	(  snake_case_,					snake_case_,					unittest.TestCase   ):






   '''simple docstring'''







   _snake_case		   =							IFPipeline
   _snake_case		   =							TEXT_TO_IMAGE_PARAMS - {'''width''', '''height''', '''latents'''}
   _snake_case		   =							TEXT_TO_IMAGE_BATCH_PARAMS
   _snake_case		   =							PipelineTesterMixin.required_optional_params - {'''latents'''}







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      return self._get_dummy_components()







   def       UpperCAmelCase				(			self ,   lowerCamelCase__ ,   lowerCamelCase__=0   ):

      '''simple docstring'''







      if str(lowerCamelCase__   ).startswith('''mps'''   ):
         UpperCamelCase       =  torch.manual_seed(lowerCamelCase__   )
      else:
         UpperCamelCase       =  torch.Generator(device=lowerCamelCase__   ).manual_seed(lowerCamelCase__   )

      UpperCamelCase       =  {
          '''prompt''': '''A painting of a squirrel eating a burger''',
          '''generator''': generator,
          '''num_inference_steps''': 2,
          '''output_type''': '''numpy''',
      }

      return inputs







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      self._test_save_load_optional_components()







   @unittest.skipIf(torch_device != '''cuda''' ,   reason='''float16 requires CUDA'''   )
   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      super().test_save_load_floataa(expected_max_diff=1e-1   )







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      self._test_attention_slicing_forward_pass(expected_max_diff=1e-2   )







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      self._test_save_load_local()







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      self._test_inference_batch_single_identical(
          expected_max_diff=1e-2 ,   )







   @unittest.skipIf(
       torch_device != '''cuda''' or not is_xformers_available() ,   reason='''XFormers attention is only available with CUDA and `xformers` installed''' ,   )
   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3   )




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






   '''simple docstring'''







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







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







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      UpperCamelCase       =  IFPipeline.from_pretrained('''DeepFloyd/IF-I-XL-v1.0''' ,   variant='''fp16''' ,   torch_dtype=torch.floataa   )

      UpperCamelCase       =  IFSuperResolutionPipeline.from_pretrained(
          '''DeepFloyd/IF-II-L-v1.0''' ,   variant='''fp16''' ,   torch_dtype=torch.floataa ,   text_encoder=lowerCamelCase__ ,   tokenizer=lowerCamelCase__   )

      # pre compute text embeddings and remove T5 to save memory

      pipe_a.text_encoder.to('''cuda'''   )

      UpperCamelCase     , UpperCamelCase       =  pipe_a.encode_prompt('''anime turtle''' ,   device='''cuda'''   )

      del pipe_a.tokenizer
      del pipe_a.text_encoder
      gc.collect()

      UpperCamelCase       =  None
      UpperCamelCase       =  None

      pipe_a.enable_model_cpu_offload()
      pipe_a.enable_model_cpu_offload()

      pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()   )
      pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()   )

      self._test_if(lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__   )

      pipe_a.remove_all_hooks()
      pipe_a.remove_all_hooks()

      # img2img

      UpperCamelCase       =  IFImgaImgPipeline(**pipe_a.components   )
      UpperCamelCase       =  IFImgaImgSuperResolutionPipeline(**pipe_a.components   )

      pipe_a.enable_model_cpu_offload()
      pipe_a.enable_model_cpu_offload()

      pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()   )
      pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()   )

      self._test_if_imgaimg(lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__   )

      pipe_a.remove_all_hooks()
      pipe_a.remove_all_hooks()

      # inpainting

      UpperCamelCase       =  IFInpaintingPipeline(**pipe_a.components   )
      UpperCamelCase       =  IFInpaintingSuperResolutionPipeline(**pipe_a.components   )

      pipe_a.enable_model_cpu_offload()
      pipe_a.enable_model_cpu_offload()

      pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()   )
      pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()   )

      self._test_if_inpainting(lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__   )







   def       UpperCAmelCase				(			self ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__   ):

      '''simple docstring'''







      _start_torch_memory_measurement()

      UpperCamelCase       =  torch.Generator(device='''cpu'''   ).manual_seed(0   )
      UpperCamelCase       =  pipe_a(
          prompt_embeds=lowerCamelCase__ ,   negative_prompt_embeds=lowerCamelCase__ ,   num_inference_steps=2 ,   generator=lowerCamelCase__ ,   output_type='''np''' ,   )

      UpperCamelCase       =  output.images[0]

      assert image.shape == (6_4, 6_4, 3)

      UpperCamelCase       =  torch.cuda.max_memory_allocated()
      assert mem_bytes < 1_3 * 1_0**9

      UpperCamelCase       =  load_numpy(
          '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy'''   )
      assert_mean_pixel_difference(lowerCamelCase__ ,   lowerCamelCase__   )

      # pipeline 2

      _start_torch_memory_measurement()

      UpperCamelCase       =  torch.Generator(device='''cpu'''   ).manual_seed(0   )

      UpperCamelCase       =  floats_tensor((1, 3, 6_4, 6_4) ,   rng=random.Random(0   )   ).to(lowerCamelCase__   )

      UpperCamelCase       =  pipe_a(
          prompt_embeds=lowerCamelCase__ ,   negative_prompt_embeds=lowerCamelCase__ ,   image=lowerCamelCase__ ,   generator=lowerCamelCase__ ,   num_inference_steps=2 ,   output_type='''np''' ,   )

      UpperCamelCase       =  output.images[0]

      assert image.shape == (2_5_6, 2_5_6, 3)

      UpperCamelCase       =  torch.cuda.max_memory_allocated()
      assert mem_bytes < 4 * 1_0**9

      UpperCamelCase       =  load_numpy(
          '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy'''   )
      assert_mean_pixel_difference(lowerCamelCase__ ,   lowerCamelCase__   )







   def       UpperCAmelCase				(			self ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__   ):

      '''simple docstring'''







      _start_torch_memory_measurement()

      UpperCamelCase       =  floats_tensor((1, 3, 6_4, 6_4) ,   rng=random.Random(0   )   ).to(lowerCamelCase__   )

      UpperCamelCase       =  torch.Generator(device='''cpu'''   ).manual_seed(0   )

      UpperCamelCase       =  pipe_a(
          prompt_embeds=lowerCamelCase__ ,   negative_prompt_embeds=lowerCamelCase__ ,   image=lowerCamelCase__ ,   num_inference_steps=2 ,   generator=lowerCamelCase__ ,   output_type='''np''' ,   )

      UpperCamelCase       =  output.images[0]

      assert image.shape == (6_4, 6_4, 3)

      UpperCamelCase       =  torch.cuda.max_memory_allocated()
      assert mem_bytes < 1_0 * 1_0**9

      UpperCamelCase       =  load_numpy(
          '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy'''   )
      assert_mean_pixel_difference(lowerCamelCase__ ,   lowerCamelCase__   )

      # pipeline 2

      _start_torch_memory_measurement()

      UpperCamelCase       =  torch.Generator(device='''cpu'''   ).manual_seed(0   )

      UpperCamelCase       =  floats_tensor((1, 3, 2_5_6, 2_5_6) ,   rng=random.Random(0   )   ).to(lowerCamelCase__   )
      UpperCamelCase       =  floats_tensor((1, 3, 6_4, 6_4) ,   rng=random.Random(0   )   ).to(lowerCamelCase__   )

      UpperCamelCase       =  pipe_a(
          prompt_embeds=lowerCamelCase__ ,   negative_prompt_embeds=lowerCamelCase__ ,   image=lowerCamelCase__ ,   original_image=lowerCamelCase__ ,   generator=lowerCamelCase__ ,   num_inference_steps=2 ,   output_type='''np''' ,   )

      UpperCamelCase       =  output.images[0]

      assert image.shape == (2_5_6, 2_5_6, 3)

      UpperCamelCase       =  torch.cuda.max_memory_allocated()
      assert mem_bytes < 4 * 1_0**9

      UpperCamelCase       =  load_numpy(
          '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy'''   )
      assert_mean_pixel_difference(lowerCamelCase__ ,   lowerCamelCase__   )







   def       UpperCAmelCase				(			self ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__   ):

      '''simple docstring'''







      _start_torch_memory_measurement()

      UpperCamelCase       =  floats_tensor((1, 3, 6_4, 6_4) ,   rng=random.Random(0   )   ).to(lowerCamelCase__   )
      UpperCamelCase       =  floats_tensor((1, 3, 6_4, 6_4) ,   rng=random.Random(1   )   ).to(lowerCamelCase__   )

      UpperCamelCase       =  torch.Generator(device='''cpu'''   ).manual_seed(0   )
      UpperCamelCase       =  pipe_a(
          prompt_embeds=lowerCamelCase__ ,   negative_prompt_embeds=lowerCamelCase__ ,   image=lowerCamelCase__ ,   mask_image=lowerCamelCase__ ,   num_inference_steps=2 ,   generator=lowerCamelCase__ ,   output_type='''np''' ,   )

      UpperCamelCase       =  output.images[0]

      assert image.shape == (6_4, 6_4, 3)

      UpperCamelCase       =  torch.cuda.max_memory_allocated()
      assert mem_bytes < 1_0 * 1_0**9

      UpperCamelCase       =  load_numpy(
          '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy'''   )
      assert_mean_pixel_difference(lowerCamelCase__ ,   lowerCamelCase__   )

      # pipeline 2

      _start_torch_memory_measurement()

      UpperCamelCase       =  torch.Generator(device='''cpu'''   ).manual_seed(0   )

      UpperCamelCase       =  floats_tensor((1, 3, 6_4, 6_4) ,   rng=random.Random(0   )   ).to(lowerCamelCase__   )
      UpperCamelCase       =  floats_tensor((1, 3, 2_5_6, 2_5_6) ,   rng=random.Random(0   )   ).to(lowerCamelCase__   )
      UpperCamelCase       =  floats_tensor((1, 3, 2_5_6, 2_5_6) ,   rng=random.Random(1   )   ).to(lowerCamelCase__   )

      UpperCamelCase       =  pipe_a(
          prompt_embeds=lowerCamelCase__ ,   negative_prompt_embeds=lowerCamelCase__ ,   image=lowerCamelCase__ ,   mask_image=lowerCamelCase__ ,   original_image=lowerCamelCase__ ,   generator=lowerCamelCase__ ,   num_inference_steps=2 ,   output_type='''np''' ,   )

      UpperCamelCase       =  output.images[0]

      assert image.shape == (2_5_6, 2_5_6, 3)

      UpperCamelCase       =  torch.cuda.max_memory_allocated()
      assert mem_bytes < 4 * 1_0**9

      UpperCamelCase       =  load_numpy(
          '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy'''   )
      assert_mean_pixel_difference(lowerCamelCase__ ,   lowerCamelCase__   )




def  __snake_case     (    ):
   torch.cuda.empty_cache()
   torch.cuda.reset_max_memory_allocated()
   torch.cuda.reset_peak_memory_stats()







'''simple docstring'''


from queue import Queue
from typing import TYPE_CHECKING, Optional


if TYPE_CHECKING:
   from ..models.auto import AutoTokenizer


class 						lowercase__	:






   '''simple docstring'''







   def       UpperCAmelCase				(			self ,   lowerCamelCase__   ):

      '''simple docstring'''







      raise NotImplementedError()







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      raise NotImplementedError()




class 						lowercase__	(  snake_case_   ):






   '''simple docstring'''







   def __init__(			self ,   lowerCamelCase__ ,   lowerCamelCase__ = False ,   **lowerCamelCase__   ):

      '''simple docstring'''







      UpperCamelCase       =  tokenizer
      UpperCamelCase       =  skip_prompt
      UpperCamelCase       =  decode_kwargs

      # variables used in the streaming process
      UpperCamelCase       =  []
      UpperCamelCase       =  0
      UpperCamelCase       =  True







   def       UpperCAmelCase				(			self ,   lowerCamelCase__   ):

      '''simple docstring'''







      if len(value.shape   ) > 1 and value.shape[0] > 1:
         raise ValueError('''TextStreamer only supports batch size 1'''   )
      elif len(value.shape   ) > 1:
         UpperCamelCase       =  value[0]

      if self.skip_prompt and self.next_tokens_are_prompt:
         UpperCamelCase       =  False
         return

      # Add the new token to the cache and decodes the entire thing.
      self.token_cache.extend(value.tolist()   )
      UpperCamelCase       =  self.tokenizer.decode(self.token_cache ,   **self.decode_kwargs   )

      # After the symbol for a new line, we flush the cache.
      if text.endswith('''\n'''   ):
         UpperCamelCase       =  text[self.print_len :]
         UpperCamelCase       =  []
         UpperCamelCase       =  0
      # If the last token is a CJK character, we print the characters.
      elif len(lowerCamelCase__   ) > 0 and self._is_chinese_char(ord(text[-1]   )   ):
         UpperCamelCase       =  text[self.print_len :]
         self.print_len += len(lowerCamelCase__   )
      # Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words,
      # which may change with the subsequent token -- there are probably smarter ways to do this!)
      else:
         UpperCamelCase       =  text[self.print_len : text.rfind(''' '''   ) + 1]
         self.print_len += len(lowerCamelCase__   )

      self.on_finalized_text(lowerCamelCase__   )







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      if len(self.token_cache   ) > 0:
         UpperCamelCase       =  self.tokenizer.decode(self.token_cache ,   **self.decode_kwargs   )
         UpperCamelCase       =  text[self.print_len :]
         UpperCamelCase       =  []
         UpperCamelCase       =  0
      else:
         UpperCamelCase       =  ''''''

      UpperCamelCase       =  True
      self.on_finalized_text(lowerCamelCase__ ,   stream_end=lowerCamelCase__   )







   def       UpperCAmelCase				(			self ,   lowerCamelCase__ ,   lowerCamelCase__ = False   ):

      '''simple docstring'''







      print(lowerCamelCase__ ,   flush=lowerCamelCase__ ,   end='''''' if not stream_end else None   )







   def       UpperCAmelCase				(			self ,   lowerCamelCase__   ):

      '''simple docstring'''







      if (
          (cp >= 0x4_E_0_0 and cp <= 0x9_F_F_F)
          or (cp >= 0x3_4_0_0 and cp <= 0x4_D_B_F)  #
          or (cp >= 0x2_0_0_0_0 and cp <= 0x2_A_6_D_F)  #
          or (cp >= 0x2_A_7_0_0 and cp <= 0x2_B_7_3_F)  #
          or (cp >= 0x2_B_7_4_0 and cp <= 0x2_B_8_1_F)  #
          or (cp >= 0x2_B_8_2_0 and cp <= 0x2_C_E_A_F)  #
          or (cp >= 0xF_9_0_0 and cp <= 0xF_A_F_F)
          or (cp >= 0x2_F_8_0_0 and cp <= 0x2_F_A_1_F)  #
      ):  #
         return True

      return False




class 						lowercase__	(  snake_case_   ):






   '''simple docstring'''







   def __init__(			self ,   lowerCamelCase__ ,   lowerCamelCase__ = False ,   lowerCamelCase__ = None ,   **lowerCamelCase__   ):

      '''simple docstring'''







      super().__init__(lowerCamelCase__ ,   lowerCamelCase__ ,   **lowerCamelCase__   )
      UpperCamelCase       =  Queue()
      UpperCamelCase       =  None
      UpperCamelCase       =  timeout







   def       UpperCAmelCase				(			self ,   lowerCamelCase__ ,   lowerCamelCase__ = False   ):

      '''simple docstring'''







      self.text_queue.put(lowerCamelCase__ ,   timeout=self.timeout   )
      if stream_end:
         self.text_queue.put(self.stop_signal ,   timeout=self.timeout   )







   def __iter__(			self   ):

      '''simple docstring'''







      return self







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      UpperCamelCase       =  self.text_queue.get(timeout=self.timeout   )
      if value == self.stop_signal:
         raise StopIteration()
      else:
         return value





