import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    PNDMScheduler,
    StableDiffusionLDMaDPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import nightly, 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


enable_full_determinism()




class        __snake_case	(					unittest.TestCase    ):
      a__				=		StableDiffusionLDMaDPipeline
      a__				=		TEXT_TO_IMAGE_PARAMS
      a__				=		TEXT_TO_IMAGE_BATCH_PARAMS
      a__				=		TEXT_TO_IMAGE_IMAGE_PARAMS



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





        '''simple docstring'''





        torch.manual_seed(0)
        a__:					Tuple      							=     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   ,      )
        a__:					Any      							=     DDIMScheduler(
            beta_start=0.00085   ,      beta_end=0.012   ,      beta_schedule='scaled_linear'   ,      clip_sample=lowercase   ,      set_alpha_to_one=lowercase   ,      )
        torch.manual_seed(0)
        a__:					Optional[Any]      							=     AutoencoderKL(
            block_out_channels=[32, 64]   ,      in_channels=6   ,      out_channels=6   ,      down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']   ,      up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']   ,      latent_channels=4   ,      )
        torch.manual_seed(0)
        a__:					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   ,      )
        a__:					List[str]      							=     CLIPTextModel(lowercase)
        a__:					Optional[int]      							=     CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip')

        a__:					Any      							=     {
            'unet': unet,
            'scheduler': scheduler,
            'vae': vae,
            'text_encoder': text_encoder,
            'tokenizer': tokenizer,
            'safety_checker': None,
            'feature_extractor': None,
        }
        return components



      def   lowerCamelCase_       (						self   ,      lowercase   ,      lowercase=0)     ->      List[str]:





        '''simple docstring'''





        if str(lowercase).startswith('mps'):
          a__:					Tuple      							=     torch.manual_seed(lowercase)
        else:
          a__:					Optional[Any]      							=     torch.Generator(device=lowercase).manual_seed(lowercase)
        a__:					Optional[Any]      							=     {
            'prompt': 'A painting of a squirrel eating a burger',
            'generator': generator,
            'num_inference_steps': 2,
            'guidance_scale': 6.0,
            'output_type': 'numpy',
        }
        return inputs



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





        '''simple docstring'''





        a__:					str      							=     'cpu'  # ensure determinism for the device-dependent torch.Generator

        a__:					Tuple      							=     self.get_dummy_components()
        a__:					str      							=     StableDiffusionLDMaDPipeline(**lowercase)
        a__:					str      							=     ldmad_pipe.to(lowercase)
        ldmad_pipe.set_progress_bar_config(disable=lowercase)

        a__:					Any      							=     self.get_dummy_inputs(lowercase)
        a__:					Any      							=     ldmad_pipe(**lowercase)
        a__:					str      							=     output.rgb, output.depth

        a__:					Dict      							=     rgb[0, -3:, -3:, -1]
        a__:					List[str]      							=     depth[0, -3:, -1]

        assert rgb.shape == (1, 64, 64, 3)
        assert depth.shape == (1, 64, 64)

        a__:					Tuple      							=     np.array(
            [0.37338176, 0.70247, 0.74203193, 0.51643604, 0.58256793, 0.60932136, 0.4181095, 0.48355877, 0.46535262])
        a__:					int      							=     np.array([103.46727, 85.812004, 87.849236])

        assert np.abs(image_slice_rgb.flatten() - expected_slice_rgb).max() < 1e-2
        assert np.abs(image_slice_depth.flatten() - expected_slice_depth).max() < 1e-2



      def   lowerCamelCase_       (						self)     ->      Tuple:





        '''simple docstring'''





        a__:					str      							=     self.get_dummy_components()
        a__:					Any      							=     StableDiffusionLDMaDPipeline(**lowercase)
        a__:					Dict      							=     ldmad_pipe.to(lowercase)
        ldmad_pipe.set_progress_bar_config(disable=lowercase)

        a__:					str      							=     self.get_dummy_inputs(lowercase)
        a__:					int      							=     3 * [inputs['prompt']]

        # forward
        a__:					Any      							=     ldmad_pipe(**lowercase)
        a__:					Any      							=     output.rgb, output.depth
        a__:					Dict      							=     rgb_slice_a[0, -3:, -3:, -1]
        a__:					List[Any]      							=     depth_slice_a[0, -3:, -1]

        a__:					List[Any]      							=     self.get_dummy_inputs(lowercase)
        a__:					int      							=     3 * [inputs.pop('prompt')]

        a__:					str      							=     ldmad_pipe.tokenizer(
            lowercase   ,      padding='max_length'   ,      max_length=ldmad_pipe.tokenizer.model_max_length   ,      truncation=lowercase   ,      return_tensors='pt'   ,      )
        a__:					List[str]      							=     text_inputs['input_ids'].to(lowercase)

        a__:					Dict      							=     ldmad_pipe.text_encoder(lowercase)[0]

        a__:					List[Any]      							=     prompt_embeds

        # forward
        a__:					Optional[int]      							=     ldmad_pipe(**lowercase)
        a__:					List[str]      							=     output.rgb, output.depth
        a__:					str      							=     rgb_slice_a[0, -3:, -3:, -1]
        a__:					Optional[Any]      							=     depth_slice_a[0, -3:, -1]

        assert np.abs(rgb_slice_a.flatten() - rgb_slice_a.flatten()).max() < 1e-4
        assert np.abs(depth_slice_a.flatten() - depth_slice_a.flatten()).max() < 1e-4



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





        '''simple docstring'''





        a__:					List[str]      							=     'cpu'  # ensure determinism for the device-dependent torch.Generator
        a__:					str      							=     self.get_dummy_components()
        a__:					int      							=     PNDMScheduler(skip_prk_steps=lowercase)
        a__:					List[Any]      							=     StableDiffusionLDMaDPipeline(**lowercase)
        a__:					Tuple      							=     ldmad_pipe.to(lowercase)
        ldmad_pipe.set_progress_bar_config(disable=lowercase)

        a__:					Union[str, Any]      							=     self.get_dummy_inputs(lowercase)
        a__:					Any      							=     'french fries'
        a__:					Optional[Any]      							=     ldmad_pipe(**lowercase   ,      negative_prompt=lowercase)

        a__:					Any      							=     output.rgb, output.depth
        a__:					Dict      							=     rgb[0, -3:, -3:, -1]
        a__:					Union[str, Any]      							=     depth[0, -3:, -1]

        assert rgb.shape == (1, 64, 64, 3)
        assert depth.shape == (1, 64, 64)

        a__:					Tuple      							=     np.array(
            [0.37044, 0.71811503, 0.7223251, 0.48603675, 0.5638391, 0.6364948, 0.42833704, 0.4901315, 0.47926217])
        a__:					Dict      							=     np.array([107.84738, 84.62802, 89.962135])
        assert np.abs(rgb_slice.flatten() - expected_slice_rgb).max() < 1e-2
        assert np.abs(depth_slice.flatten() - expected_slice_depth).max() < 1e-2







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



      def   lowerCamelCase_       (						self)     ->      List[Any]:





        '''simple docstring'''





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



      def   lowerCamelCase_       (						self   ,      lowercase   ,      lowercase="cpu"   ,      lowercase=torch.floataa   ,      lowercase=0)     ->      Tuple:





        '''simple docstring'''





        a__:					int      							=     torch.Generator(device=lowercase).manual_seed(lowercase)
        a__:					Optional[Any]      							=     np.random.RandomState(lowercase).standard_normal((1, 4, 64, 64))
        a__:					Any      							=     torch.from_numpy(lowercase).to(device=lowercase   ,      dtype=lowercase)
        a__:					str      							=     {
            'prompt': 'a photograph of an astronaut riding a horse',
            'latents': latents,
            'generator': generator,
            'num_inference_steps': 3,
            'guidance_scale': 7.5,
            'output_type': 'numpy',
        }
        return inputs



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





        '''simple docstring'''





        a__:					List[str]      							=     StableDiffusionLDMaDPipeline.from_pretrained('Intel/ldm3d')
        a__:					Optional[Any]      							=     ldmad_pipe.to(lowercase)
        ldmad_pipe.set_progress_bar_config(disable=lowercase)

        a__:					Optional[Any]      							=     self.get_inputs(lowercase)
        a__:					Union[str, Any]      							=     ldmad_pipe(**lowercase)
        a__:					Optional[Any]      							=     output.rgb, output.depth
        a__:					str      							=     rgb[0, -3:, -3:, -1].flatten()
        a__:					str      							=     rgb[0, -3:, -1].flatten()

        assert rgb.shape == (1, 5_12, 5_12, 3)
        assert depth.shape == (1, 5_12, 5_12)

        a__:					Optional[Any]      							=     np.array(
            [0.53805465, 0.56707305, 0.5486515, 0.57012236, 0.5814511, 0.56253487, 0.54843014, 0.55092263, 0.6459706])
        a__:					str      							=     np.array(
            [0.9263781, 0.6678672, 0.5486515, 0.92202145, 0.67831135, 0.56253487, 0.9241694, 0.7551478, 0.6459706])
        assert np.abs(rgb_slice - expected_slice_rgb).max() < 3e-3
        assert np.abs(depth_slice - expected_slice_depth).max() < 3e-3







@nightly
@require_torch_gpu
class        __snake_case	(					unittest.TestCase    ):



      def   lowerCamelCase_       (						self)     ->      int:





        '''simple docstring'''





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



      def   lowerCamelCase_       (						self   ,      lowercase   ,      lowercase="cpu"   ,      lowercase=torch.floataa   ,      lowercase=0)     ->      Dict:





        '''simple docstring'''





        a__:					Optional[Any]      							=     torch.Generator(device=lowercase).manual_seed(lowercase)
        a__:					str      							=     np.random.RandomState(lowercase).standard_normal((1, 4, 64, 64))
        a__:					Dict      							=     torch.from_numpy(lowercase).to(device=lowercase   ,      dtype=lowercase)
        a__:					str      							=     {
            'prompt': 'a photograph of an astronaut riding a horse',
            'latents': latents,
            'generator': generator,
            'num_inference_steps': 50,
            'guidance_scale': 7.5,
            'output_type': 'numpy',
        }
        return inputs



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





        '''simple docstring'''





        a__:					List[str]      							=     StableDiffusionLDMaDPipeline.from_pretrained('Intel/ldm3d').to(lowercase)
        ldmad_pipe.set_progress_bar_config(disable=lowercase)

        a__:					List[str]      							=     self.get_inputs(lowercase)
        a__:					Dict      							=     ldmad_pipe(**lowercase)
        a__:					Dict      							=     output.rgb, output.depth

        a__:					Union[str, Any]      							=     0.495586
        a__:					Union[str, Any]      							=     0.33795515
        a__:					str      							=     112.48518
        a__:					List[Any]      							=     98.489746
        assert np.abs(expected_rgb_mean - rgb.mean()) < 1e-3
        assert np.abs(expected_rgb_std - rgb.std()) < 1e-3
        assert np.abs(expected_depth_mean - depth.mean()) < 1e-3
        assert np.abs(expected_depth_std - depth.std()) < 1e-3



      def   lowerCamelCase_       (						self)     ->      str:





        '''simple docstring'''





        a__:					Union[str, Any]      							=     StableDiffusionLDMaDPipeline.from_pretrained('Intel/ldm3d-4c').to(lowercase)
        ldmad_pipe.set_progress_bar_config(disable=lowercase)

        a__:					List[str]      							=     self.get_inputs(lowercase)
        a__:					Union[str, Any]      							=     ldmad_pipe(**lowercase)
        a__:					List[Any]      							=     output.rgb, output.depth

        a__:					Optional[Any]      							=     0.4194127
        a__:					Optional[Any]      							=     0.35375586
        a__:					int      							=     0.5638502
        a__:					Dict      							=     0.34686103

        assert rgb.shape == (1, 5_12, 5_12, 3)
        assert depth.shape == (1, 5_12, 5_12, 1)
        assert np.abs(expected_rgb_mean - rgb.mean()) < 1e-3
        assert np.abs(expected_rgb_std - rgb.std()) < 1e-3
        assert np.abs(expected_depth_mean - depth.mean()) < 1e-3
        assert np.abs(expected_depth_std - depth.std()) < 1e-3



"""simple docstring"""
def 						__a       (     _SCREAMING_SNAKE_CASE       )     ->bool:
  return credit_card_number.startswith(('34', '35', '37', '4', '5', '6')       )







def 						__a       (     _SCREAMING_SNAKE_CASE       )     ->bool:
  a__:					Any      							=     credit_card_number
  a__:					Tuple      							=     0
  a__:					List[str]      							=     len(_SCREAMING_SNAKE_CASE       ) - 2
  for i in range(_SCREAMING_SNAKE_CASE		,					-1		,					-2       ):
    #  double the value of every second digit
    a__:					Tuple      							=     int(cc_number[i]       )
    digit *= 2
    # If doubling of a number results in a two digit number
    # i.e greater than 9(e.g., 6 × 2 = 12),
    # then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6),
    # to get a single digit number.
    if digit > 9:
      digit %= 10
      digit += 1
    a__:					Optional[Any]      							=     cc_number[:i] + str(_SCREAMING_SNAKE_CASE       ) + cc_number[i + 1 :]
    total += digit

  # Sum up the remaining digits
  for i in range(len(_SCREAMING_SNAKE_CASE       ) - 1		,					-1		,					-2       ):
    total += int(cc_number[i]       )

  return total % 10 == 0







def 						__a       (     _SCREAMING_SNAKE_CASE       )     ->bool:
  a__:					Optional[int]      							=     F'{credit_card_number} is an invalid credit card number because'
  if not credit_card_number.isdigit():
    print(F'{error_message} it has nonnumerical characters.'       )
    return False

  if not 13 <= len(_SCREAMING_SNAKE_CASE       ) <= 16:
    print(F'{error_message} of its length.'       )
    return False

  if not validate_initial_digits(_SCREAMING_SNAKE_CASE       ):
    print(F'{error_message} of its first two digits.'       )
    return False

  if not luhn_validation(_SCREAMING_SNAKE_CASE       ):
    print(F'{error_message} it fails the Luhn check.'       )
    return False

  print(F'{credit_card_number} is a valid credit card number.'       )
  return True


if __name__ == "__main__":
 import doctest

 doctest.testmod()
 validate_credit_card_number('4111111111111111')
 validate_credit_card_number('32323')


