

import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMParallelScheduler,
    DDPMParallelScheduler,
    StableDiffusionParadigmsPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    require_torch_gpu,
)

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()



class SCREAMING_SNAKE_CASE	(  a_   ,							a_   ,							unittest.TestCase ):
  """simple docstring"""






  lowerCamelCase    :			List[Any]						      =StableDiffusionParadigmsPipeline
  lowerCamelCase    :			Tuple						      =TEXT_TO_IMAGE_PARAMS
  lowerCamelCase    :			List[Any]						      =TEXT_TO_IMAGE_BATCH_PARAMS
  lowerCamelCase    :			Union[str, Any]						      =TEXT_TO_IMAGE_IMAGE_PARAMS
  lowerCamelCase    :			Optional[Any]						      =TEXT_TO_IMAGE_IMAGE_PARAMS







  def        SCREAMING_SNAKE_CASE    (			self :    Any    )							->	str:






     """simple docstring"""







     torch.manual_seed(0    )
     __lowerCAmelCase  :			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       ,							attention_head_dim=(2, 4)       ,							use_linear_projection=lowerCAmelCase       ,							)
     __lowerCAmelCase  :			Union[str, Any]					    =						DDIMParallelScheduler(
         beta_start=0.0_0085       ,							beta_end=0.012       ,							beta_schedule="""scaled_linear"""       ,							clip_sample=lowerCAmelCase       ,							set_alpha_to_one=lowerCAmelCase       ,							)
     torch.manual_seed(0    )
     __lowerCAmelCase  :			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       ,							sample_size=1_28       ,							)
     torch.manual_seed(0    )
     __lowerCAmelCase  :			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       ,							hidden_act="""gelu"""       ,							projection_dim=5_12       ,							)
     __lowerCAmelCase  :			Dict					    =						CLIPTextModel(lowerCAmelCase    )
     __lowerCAmelCase  :			Optional[int]					    =						CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""    )

     __lowerCAmelCase  :			List[Any]					    =						{
         """unet""": unet,
         """scheduler""": scheduler,
         """vae""": vae,
         """text_encoder""": text_encoder,
         """tokenizer""": tokenizer,
         """safety_checker""": None,
         """feature_extractor""": None,
     }
     return components







  def        SCREAMING_SNAKE_CASE    (			self :    List[str]       ,							lowerCAmelCase :    List[str]       ,							lowerCAmelCase :    str=0    )							->	str:






     """simple docstring"""







     if str(lowerCAmelCase    ).startswith("""mps"""    ):
        __lowerCAmelCase  :			List[Any]					    =						torch.manual_seed(lowerCAmelCase    )
     else:
        __lowerCAmelCase  :			Optional[int]					    =						torch.Generator(device=lowerCAmelCase    ).manual_seed(lowerCAmelCase    )
     __lowerCAmelCase  :			Any					    =						{
         """prompt""": """a photograph of an astronaut riding a horse""",
         """generator""": generator,
         """num_inference_steps""": 10,
         """guidance_scale""": 6.0,
         """output_type""": """numpy""",
         """parallel""": 3,
         """debug""": True,
     }
     return inputs







  def        SCREAMING_SNAKE_CASE    (			self :    List[str]    )							->	int:






     """simple docstring"""







     __lowerCAmelCase  :			Union[str, Any]					    =						"""cpu"""  # ensure determinism for the device-dependent torch.Generator
     __lowerCAmelCase  :			Union[str, Any]					    =						self.get_dummy_components()
     __lowerCAmelCase  :			List[str]					    =						StableDiffusionParadigmsPipeline(**lowerCAmelCase    )
     __lowerCAmelCase  :			Optional[Any]					    =						sd_pipe.to(lowerCAmelCase    )
     sd_pipe.set_progress_bar_config(disable=lowerCAmelCase    )

     __lowerCAmelCase  :			Optional[Any]					    =						self.get_dummy_inputs(lowerCAmelCase    )
     __lowerCAmelCase  :			Union[str, Any]					    =						sd_pipe(**lowerCAmelCase    ).images
     __lowerCAmelCase  :			Union[str, Any]					    =						image[0, -3:, -3:, -1]
     assert image.shape == (1, 64, 64, 3)

     __lowerCAmelCase  :			int					    =						np.array([0.4773, 0.5417, 0.4723, 0.4925, 0.5631, 0.4752, 0.5240, 0.4935, 0.5023]    )

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







  def        SCREAMING_SNAKE_CASE    (			self :    Optional[Any]    )							->	Tuple:






     """simple docstring"""







     __lowerCAmelCase  :			Optional[Any]					    =						"""cpu"""  # ensure determinism for the device-dependent torch.Generator
     __lowerCAmelCase  :			str					    =						self.get_dummy_components()
     torch.manual_seed(0    )
     __lowerCAmelCase  :			List[Any]					    =						DDPMParallelScheduler()
     torch.manual_seed(0    )
     __lowerCAmelCase  :			Any					    =						StableDiffusionParadigmsPipeline(**lowerCAmelCase    )
     __lowerCAmelCase  :			Any					    =						sd_pipe.to(lowerCAmelCase    )
     sd_pipe.set_progress_bar_config(disable=lowerCAmelCase    )

     __lowerCAmelCase  :			Dict					    =						self.get_dummy_inputs(lowerCAmelCase    )
     __lowerCAmelCase  :			Dict					    =						sd_pipe(**lowerCAmelCase    ).images
     __lowerCAmelCase  :			str					    =						image[0, -3:, -3:, -1]
     assert image.shape == (1, 64, 64, 3)

     __lowerCAmelCase  :			List[str]					    =						np.array([0.3573, 0.4420, 0.4960, 0.4799, 0.3796, 0.3879, 0.4819, 0.4365, 0.4468]    )

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







  def        SCREAMING_SNAKE_CASE    (			self :    List[Any]    )							->	Optional[Any]:






     """simple docstring"""







     super().test_inference_batch_consistent(batch_sizes=[1, 2]    )







  def        SCREAMING_SNAKE_CASE    (			self :    Optional[Any]    )							->	Any:






     """simple docstring"""







     super().test_inference_batch_single_identical(batch_size=2       ,							expected_max_diff=3e-3    )







  def        SCREAMING_SNAKE_CASE    (			self :    Dict    )							->	Tuple:






     """simple docstring"""







     __lowerCAmelCase  :			List[str]					    =						"""cpu"""  # ensure determinism for the device-dependent torch.Generator
     __lowerCAmelCase  :			Union[str, Any]					    =						self.get_dummy_components()
     __lowerCAmelCase  :			str					    =						StableDiffusionParadigmsPipeline(**lowerCAmelCase    )
     __lowerCAmelCase  :			str					    =						sd_pipe.to(lowerCAmelCase    )
     sd_pipe.set_progress_bar_config(disable=lowerCAmelCase    )

     __lowerCAmelCase  :			List[Any]					    =						self.get_dummy_inputs(lowerCAmelCase    )
     __lowerCAmelCase  :			Optional[int]					    =						"""french fries"""
     __lowerCAmelCase  :			Union[str, Any]					    =						sd_pipe(**lowerCAmelCase       ,							negative_prompt=lowerCAmelCase    )
     __lowerCAmelCase  :			Tuple					    =						output.images
     __lowerCAmelCase  :			int					    =						image[0, -3:, -3:, -1]

     assert image.shape == (1, 64, 64, 3)

     __lowerCAmelCase  :			List[Any]					    =						np.array([0.4771, 0.5420, 0.4683, 0.4918, 0.5636, 0.4725, 0.5230, 0.4923, 0.5015]    )

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






@slow
@require_torch_gpu
class SCREAMING_SNAKE_CASE	(  unittest.TestCase ):
  """simple docstring"""






  def        SCREAMING_SNAKE_CASE    (			self :    Dict    )							->	Any:






     """simple docstring"""







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







  def        SCREAMING_SNAKE_CASE    (			self :    Optional[int]       ,							lowerCAmelCase :    List[Any]=0    )							->	List[Any]:






     """simple docstring"""







     __lowerCAmelCase  :			Optional[int]					    =						torch.Generator(device=lowerCAmelCase    ).manual_seed(lowerCAmelCase    )
     __lowerCAmelCase  :			Any					    =						{
         """prompt""": """a photograph of an astronaut riding a horse""",
         """generator""": generator,
         """num_inference_steps""": 10,
         """guidance_scale""": 7.5,
         """output_type""": """numpy""",
         """parallel""": 3,
         """debug""": True,
     }
     return inputs







  def        SCREAMING_SNAKE_CASE    (			self :    Tuple    )							->	List[Any]:






     """simple docstring"""







     __lowerCAmelCase  :			Optional[int]					    =						"""stabilityai/stable-diffusion-2-base"""
     __lowerCAmelCase  :			Tuple					    =						DDIMParallelScheduler.from_pretrained(lowerCAmelCase       ,							subfolder="""scheduler"""    )
     __lowerCAmelCase  :			Union[str, Any]					    =						StableDiffusionParadigmsPipeline.from_pretrained(lowerCAmelCase       ,							scheduler=lowerCAmelCase       ,							safety_checker=lowerCAmelCase    )
     pipe.to(lowerCAmelCase    )
     pipe.set_progress_bar_config(disable=lowerCAmelCase    )
     pipe.enable_attention_slicing()

     __lowerCAmelCase  :			Union[str, Any]					    =						self.get_inputs()
     __lowerCAmelCase  :			List[Any]					    =						pipe(**lowerCAmelCase    ).images
     __lowerCAmelCase  :			List[str]					    =						image[0, -3:, -3:, -1].flatten()

     assert image.shape == (1, 5_12, 5_12, 3)

     __lowerCAmelCase  :			List[str]					    =						np.array([0.9622, 0.9602, 0.9748, 0.9591, 0.9630, 0.9691, 0.9661, 0.9631, 0.9741]    )

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





from __future__ import annotations

import os



class SCREAMING_SNAKE_CASE	:
  """simple docstring"""






  lowerCamelCase    :			Union[str, Any]						      =(
      "High card",
      "One pair",
      "Two pairs",
      "Three of a kind",
      "Straight",
      "Flush",
      "Full house",
      "Four of a kind",
      "Straight flush",
      "Royal flush",
  )

  lowerCamelCase    :			Dict						      =(
      "",  # placeholder as tuples are zero-indexed
      "One",
      "Two",
      "Three",
      "Four",
      "Five",
      "Six",
      "Seven",
      "Eight",
      "Nine",
      "Ten",
      "Jack",
      "Queen",
      "King",
      "Ace",
  )







  def __init__(			self :    Tuple       ,							lowerCAmelCase :    str    )							->	None:






     """simple docstring"""







     if not isinstance(lowerCAmelCase       ,							lowerCAmelCase    ):
        __lowerCAmelCase  :			Tuple					    =						f'''Hand should be of type \'str\': {hand!r}'''
        raise TypeError(lowerCAmelCase    )
     # split removes duplicate whitespaces so no need of strip
     if len(hand.split(""" """    )    ) != 5:
        __lowerCAmelCase  :			Any					    =						f'''Hand should contain only 5 cards: {hand!r}'''
        raise ValueError(lowerCAmelCase    )
     __lowerCAmelCase  :			int					    =						hand
     __lowerCAmelCase  :			Any					    =						0
     __lowerCAmelCase  :			str					    =						0
     __lowerCAmelCase    ,__lowerCAmelCase  :			List[str]					    =						self._internal_state()
     __lowerCAmelCase  :			int					    =						self._get_hand_type()
     __lowerCAmelCase  :			Any					    =						self._card_values[0]







  @property
  def        SCREAMING_SNAKE_CASE    (			self :    Union[str, Any]    )							->	Optional[int]:






     """simple docstring"""







     return self._hand







  def        SCREAMING_SNAKE_CASE    (			self :    Dict       ,							lowerCAmelCase :    PokerHand    )							->	str:






     """simple docstring"""







     if self._hand_type > other._hand_type:
        return "Win"
     elif self._hand_type < other._hand_type:
        return "Loss"
     elif self._first_pair == other._first_pair:
        if self._second_pair == other._second_pair:
           return self._compare_cards(lowerCAmelCase    )
        else:
           return "Win" if self._second_pair > other._second_pair else "Loss"
     return "Win" if self._first_pair > other._first_pair else "Loss"







  def        SCREAMING_SNAKE_CASE    (			self :    int    )							->	str:






     """simple docstring"""







     __lowerCAmelCase  :			Optional[int]					    =						PokerHand._HAND_NAME[self._hand_type - 14]
     __lowerCAmelCase  :			str					    =						PokerHand._CARD_NAME[self._high_card]
     __lowerCAmelCase  :			Optional[Any]					    =						PokerHand._CARD_NAME[self._first_pair]
     __lowerCAmelCase  :			Any					    =						PokerHand._CARD_NAME[self._second_pair]
     if self._hand_type in [22, 19, 18]:
        return name + f''', {high}-high'''
     elif self._hand_type in [21, 17, 15]:
        return name + f''', {paira}s'''
     elif self._hand_type in [20, 16]:
        __lowerCAmelCase  :			List[str]					    =						"""over""" if self._hand_type == 20 else """and"""
        return name + f''', {paira}s {join} {paira}s'''
     elif self._hand_type == 23:
        return name
     else:
        return name + f''', {high}'''







  def        SCREAMING_SNAKE_CASE    (			self :    Dict       ,							lowerCAmelCase :    PokerHand    )							->	str:






     """simple docstring"""







     for index, card_value in enumerate(self._card_values    ):
        if card_value != other._card_values[index]:
           return "Win" if card_value > other._card_values[index] else "Loss"
     return "Tie"







  def        SCREAMING_SNAKE_CASE    (			self :    Optional[int]    )							->	int:






     """simple docstring"""







     if self._is_flush():
        if self._is_five_high_straight() or self._is_straight():
           return 23 if sum(self._card_values    ) == 60 else 22
        return 19
     elif self._is_five_high_straight() or self._is_straight():
        return 18
     return 14 + self._is_same_kind()







  def        SCREAMING_SNAKE_CASE    (			self :    List[Any]    )							->	bool:






     """simple docstring"""







     return len(self._card_suit    ) == 1







  def        SCREAMING_SNAKE_CASE    (			self :    List[str]    )							->	bool:






     """simple docstring"""







     if sorted(self._card_values    ) == [2, 3, 4, 5, 14]:
        if self._card_values[0] == 14:
           # Remember, our list is sorted in reverse order
           __lowerCAmelCase  :			Optional[Any]					    =						self._card_values.pop(0    )
           self._card_values.append(lowerCAmelCase    )
        return True
     return False







  def        SCREAMING_SNAKE_CASE    (			self :    List[str]    )							->	bool:






     """simple docstring"""







     for i in range(4    ):
        if self._card_values[i] - self._card_values[i + 1] != 1:
           return False
     return True







  def        SCREAMING_SNAKE_CASE    (			self :    Optional[int]    )							->	int:






     """simple docstring"""







     __lowerCAmelCase  :			str					    =						0
     for i in range(4    ):
        # Compare two cards at a time, if they are same increase 'kind',
        # add the value of the card to val1, if it is repeating again we
        # will add 2 to 'kind' as there are now 3 cards with same value.
        # If we get card of different value than val1, we will do the same
        # thing with val2
        if self._card_values[i] == self._card_values[i + 1]:
           if not vala:
              __lowerCAmelCase  :			List[str]					    =						self._card_values[i]
              kind += 1
           elif vala == self._card_values[i]:
              kind += 2
           elif not vala:
              __lowerCAmelCase  :			Optional[Any]					    =						self._card_values[i]
              kind += 1
           elif vala == self._card_values[i]:
              kind += 2
        # For consistency in hand type (look at note in _get_hand_type function)
     __lowerCAmelCase  :			List[Any]					    =						kind + 2 if kind in [4, 5] else kind
     # first meaning first pair to compare in 'compare_with'
     __lowerCAmelCase  :			Optional[int]					    =						max(lowerCAmelCase       ,							lowerCAmelCase    )
     __lowerCAmelCase  :			Optional[Any]					    =						min(lowerCAmelCase       ,							lowerCAmelCase    )
     # If it's full house (three count pair + two count pair), make sure
     # first pair is three count and if not then switch them both.
     if kind == 6 and self._card_values.count(lowerCAmelCase    ) != 3:
        __lowerCAmelCase    ,__lowerCAmelCase  :			Tuple					    =						second, first
     __lowerCAmelCase  :			Optional[Any]					    =						first
     __lowerCAmelCase  :			Union[str, Any]					    =						second
     return kind







  def        SCREAMING_SNAKE_CASE    (			self :    List[Any]    )							->	tuple[list[int], set[str]]:






     """simple docstring"""







     __lowerCAmelCase  :			dict					    =						{"T": "10", "J": "11", "Q": "12", "K": "13", "A": "14"}
     __lowerCAmelCase  :			Optional[Any]					    =						self._hand.translate(str.maketrans(lowerCAmelCase    )    ).split()
     __lowerCAmelCase  :			List[str]					    =						[int(card[:-1]    ) for card in new_hand]
     __lowerCAmelCase  :			str					    =						{card[-1] for card in new_hand}
     return sorted(lowerCAmelCase       ,							reverse=lowerCAmelCase    ), card_suit







  def __repr__(			self :    List[str]    )							->	Any:






     """simple docstring"""







     return f'''{self.__class__}("{self._hand}")'''







  def __str__(			self :    Any    )							->	Any:






     """simple docstring"""







     return self._hand







  def __eq__(			self :    Union[str, Any]       ,							lowerCAmelCase :    List[Any]    )							->	Union[str, Any]:






     """simple docstring"""







     if isinstance(lowerCAmelCase       ,							lowerCAmelCase    ):
        return self.compare_with(lowerCAmelCase    ) == "Tie"
     return NotImplemented







  def __lt__(			self :    Dict       ,							lowerCAmelCase :    str    )							->	List[str]:






     """simple docstring"""







     if isinstance(lowerCAmelCase       ,							lowerCAmelCase    ):
        return self.compare_with(lowerCAmelCase    ) == "Loss"
     return NotImplemented







  def __le__(			self :    str       ,							lowerCAmelCase :    int    )							->	Union[str, Any]:






     """simple docstring"""







     if isinstance(lowerCAmelCase       ,							lowerCAmelCase    ):
        return self < other or self == other
     return NotImplemented







  def __gt__(			self :    Dict       ,							lowerCAmelCase :    str    )							->	Optional[Any]:






     """simple docstring"""







     if isinstance(lowerCAmelCase       ,							lowerCAmelCase    ):
        return not self < other and self != other
     return NotImplemented







  def __ge__(			self :    Tuple       ,							lowerCAmelCase :    Tuple    )							->	Dict:






     """simple docstring"""







     if isinstance(lowerCAmelCase       ,							lowerCAmelCase    ):
        return not self < other
     return NotImplemented







  def __hash__(			self :    List[str]    )							->	str:






     """simple docstring"""







     return object.__hash__(self    )






def 	snake_case_      ()			->	int:
   # Solution for problem number 54 from Project Euler
   # Input from poker_hands.txt file
   __lowerCAmelCase  :			str					    =						0
   __lowerCAmelCase  :			List[str]					    =						os.path.abspath(os.path.dirname(__A     )     )
   __lowerCAmelCase  :			Optional[Any]					    =						os.path.join(__A					,   """poker_hands.txt"""     )
   with open(__A     ) as file_hand:
      for line in file_hand:
         __lowerCAmelCase  :			Union[str, Any]					    =						line[:1_4].strip()
         __lowerCAmelCase  :			Optional[int]					    =						line[1_5:].strip()
         __lowerCAmelCase    ,__lowerCAmelCase  :			List[str]					    =						PokerHand(__A     ), PokerHand(__A     )
         __lowerCAmelCase  :			List[str]					    =						player.compare_with(__A     )
         if output == "Win":
            answer += 1
   return answer


if __name__ == "__main__":
   solution()


