





import unittest

import numpy as np
import torch
from torch import nn
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModelWithProjection,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import KandinskyPriorPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()

class   __snake_case	(			_a       ,				unittest.TestCase   ):






    '''simple docstring'''
    _lowerCAmelCase     =	KandinskyPriorPipeline
    _lowerCAmelCase     =	["""prompt"""]
    _lowerCAmelCase     =	["""prompt""", """negative_prompt"""]
    _lowerCAmelCase     =	[
        """num_images_per_prompt""",
        """generator""",
        """num_inference_steps""",
        """latents""",
        """negative_prompt""",
        """guidance_scale""",
        """output_type""",
        """return_dict""",
    ]
    _lowerCAmelCase     =	False





    @property
    def 	A		(   self						:		str							):

      """simple docstring"""





      return 32





    @property
    def 	A		(   self						:		Tuple							):

      """simple docstring"""





      return 32





    @property
    def 	A		(   self						:		List[str]							):

      """simple docstring"""





      return self.time_input_dim





    @property
    def 	A		(   self						:		Any							):

      """simple docstring"""





      return self.time_input_dim * 4





    @property
    def 	A		(   self						:		Tuple							):

      """simple docstring"""





      return 100





    @property
    def 	A		(   self						:		Union[str, Any]							):

      """simple docstring"""





      __lowerCAmelCase			=				CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''							)
      return tokenizer





    @property
    def 	A		(   self						:		List[Any]							):

      """simple docstring"""





      torch.manual_seed(0							)
      __lowerCAmelCase			=				CLIPTextConfig(
          bos_token_id=0			,						eos_token_id=2			,						hidden_size=self.text_embedder_hidden_size			,						projection_dim=self.text_embedder_hidden_size			,						intermediate_size=37			,						layer_norm_eps=1e-05			,						num_attention_heads=4			,						num_hidden_layers=5			,						pad_token_id=1			,						vocab_size=1_000			,						)
      return CLIPTextModelWithProjection(snake_case							)





    @property
    def 	A		(   self						:		Dict							):

      """simple docstring"""





      torch.manual_seed(0							)

      __lowerCAmelCase			=				{
          '''num_attention_heads''': 2,
          '''attention_head_dim''': 12,
          '''embedding_dim''': self.text_embedder_hidden_size,
          '''num_layers''': 1,
      }

      __lowerCAmelCase			=				PriorTransformer(**snake_case							)
      # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
      __lowerCAmelCase			=				nn.Parameter(torch.ones(model.clip_std.shape							)							)
      return model





    @property
    def 	A		(   self						:		List[Any]							):

      """simple docstring"""





      torch.manual_seed(0							)
      __lowerCAmelCase			=				CLIPVisionConfig(
          hidden_size=self.text_embedder_hidden_size			,						image_size=224			,						projection_dim=self.text_embedder_hidden_size			,						intermediate_size=37			,						num_attention_heads=4			,						num_channels=3			,						num_hidden_layers=5			,						patch_size=14			,						)

      __lowerCAmelCase			=				CLIPVisionModelWithProjection(snake_case							)
      return model





    @property
    def 	A		(   self						:		Union[str, Any]							):

      """simple docstring"""





      __lowerCAmelCase			=				CLIPImageProcessor(
          crop_size=224			,						do_center_crop=snake_case			,						do_normalize=snake_case			,						do_resize=snake_case			,						image_mean=[0.4814_5466, 0.457_8275, 0.4082_1073]			,						image_std=[0.2686_2954, 0.2613_0258, 0.2757_7711]			,						resample=3			,						size=224			,						)

      return image_processor





    def 	A		(   self						:		Optional[Any]							):

      """simple docstring"""





      __lowerCAmelCase			=				self.dummy_prior
      __lowerCAmelCase			=				self.dummy_image_encoder
      __lowerCAmelCase			=				self.dummy_text_encoder
      __lowerCAmelCase			=				self.dummy_tokenizer
      __lowerCAmelCase			=				self.dummy_image_processor

      __lowerCAmelCase			=				UnCLIPScheduler(
          variance_type='''fixed_small_log'''			,						prediction_type='''sample'''			,						num_train_timesteps=1_000			,						clip_sample=snake_case			,						clip_sample_range=10.0			,						)

      __lowerCAmelCase			=				{
          '''prior''': prior,
          '''image_encoder''': image_encoder,
          '''text_encoder''': text_encoder,
          '''tokenizer''': tokenizer,
          '''scheduler''': scheduler,
          '''image_processor''': image_processor,
      }

      return components





    def 	A		(   self						:		Optional[int]			,						snake_case						:		Dict			,						snake_case						:		List[str]=0							):

      """simple docstring"""





      if str(snake_case							).startswith('''mps'''							):
        __lowerCAmelCase			=				torch.manual_seed(snake_case							)
      else:
        __lowerCAmelCase			=				torch.Generator(device=snake_case							).manual_seed(snake_case							)
      __lowerCAmelCase			=				{
          '''prompt''': '''horse''',
          '''generator''': generator,
          '''guidance_scale''': 4.0,
          '''num_inference_steps''': 2,
          '''output_type''': '''np''',
      }
      return inputs





    def 	A		(   self						:		List[str]							):

      """simple docstring"""





      __lowerCAmelCase			=				'''cpu'''

      __lowerCAmelCase			=				self.get_dummy_components()

      __lowerCAmelCase			=				self.pipeline_class(**snake_case							)
      __lowerCAmelCase			=				pipe.to(snake_case							)

      pipe.set_progress_bar_config(disable=snake_case							)

      __lowerCAmelCase			=				pipe(**self.get_dummy_inputs(snake_case							)							)
      __lowerCAmelCase			=				output.image_embeds

      __lowerCAmelCase			=				pipe(
          **self.get_dummy_inputs(snake_case							)			,						return_dict=snake_case			,						)[0]

      __lowerCAmelCase			=				image[0, -10:]
      __lowerCAmelCase			=				image_from_tuple[0, -10:]

      assert image.shape == (1, 32)

      __lowerCAmelCase			=				np.array(
          [-0.0532, 1.7120, 0.3656, -1.0852, -0.8946, -1.1756, 0.4348, 0.2482, 0.5146, -0.1156]							)

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





    @skip_mps
    def 	A		(   self						:		Tuple							):

      """simple docstring"""





      __lowerCAmelCase			=				torch_device == '''cpu'''
      __lowerCAmelCase			=				True
      __lowerCAmelCase			=				False

      self._test_inference_batch_single_identical(
          test_max_difference=snake_case			,						relax_max_difference=snake_case			,						test_mean_pixel_difference=snake_case			,						)





    @skip_mps
    def 	A		(   self						:		List[str]							):

      """simple docstring"""





      __lowerCAmelCase			=				torch_device == '''cpu'''
      __lowerCAmelCase			=				False

      self._test_attention_slicing_forward_pass(
          test_max_difference=snake_case			,						test_mean_pixel_difference=snake_case			,						)







import subprocess
from argparse import ArgumentParser
from typing import List, Union

from huggingface_hub.hf_api import HfFolder, create_repo, whoami
from requests.exceptions import HTTPError

from . import BaseTransformersCLICommand

class   __snake_case				(			_a   ):






    '''simple docstring'''





    @staticmethod
    def 	A		(   snake_case						:		ArgumentParser							):

      """simple docstring"""





      __lowerCAmelCase			=				parser.add_parser('''login'''			,						help='''Log in using the same credentials as on huggingface.co'''							)
      login_parser.set_defaults(func=lambda snake_case							: LoginCommand(snake_case							)							)
      __lowerCAmelCase			=				parser.add_parser('''whoami'''			,						help='''Find out which huggingface.co account you are logged in as.'''							)
      whoami_parser.set_defaults(func=lambda snake_case							: WhoamiCommand(snake_case							)							)
      __lowerCAmelCase			=				parser.add_parser('''logout'''			,						help='''Log out'''							)
      logout_parser.set_defaults(func=lambda snake_case							: LogoutCommand(snake_case							)							)

      # new system: git-based repo system
      __lowerCAmelCase			=				parser.add_parser(
          '''repo'''			,						help='''Deprecated: use `huggingface-cli` instead. Commands to interact with your huggingface.co repos.'''			,						)
      __lowerCAmelCase			=				repo_parser.add_subparsers(
          help='''Deprecated: use `huggingface-cli` instead. huggingface.co repos related commands'''							)
      __lowerCAmelCase			=				repo_subparsers.add_parser(
          '''create'''			,						help='''Deprecated: use `huggingface-cli` instead. Create a new repo on huggingface.co'''							)
      repo_create_parser.add_argument(
          '''name'''			,						type=snake_case			,						help='''Name for your model\'s repo. Will be namespaced under your username to build the model id.'''			,						)
      repo_create_parser.add_argument('''--organization'''			,						type=snake_case			,						help='''Optional: organization namespace.'''							)
      repo_create_parser.add_argument('''-y'''			,						'''--yes'''			,						action='''store_true'''			,						help='''Optional: answer Yes to the prompt'''							)
      repo_create_parser.set_defaults(func=lambda snake_case							: RepoCreateCommand(snake_case							)							)


class   __snake_case				:






    '''simple docstring'''
    _lowerCAmelCase     =	"""\u001b[1m"""
    _lowerCAmelCase     =	"""\u001b[31m"""
    _lowerCAmelCase     =	"""\u001b[90m"""
    _lowerCAmelCase     =	"""\u001b[0m"""





    @classmethod
    def 	A		(   cls						:		str			,						snake_case						:		Optional[int]							):

      """simple docstring"""





      return f'''{cls._bold}{s}{cls._reset}'''





    @classmethod
    def 	A		(   cls						:		Optional[Any]			,						snake_case						:		str							):

      """simple docstring"""





      return f'''{cls._bold}{cls._red}{s}{cls._reset}'''





    @classmethod
    def 	A		(   cls						:		Dict			,						snake_case						:		List[Any]							):

      """simple docstring"""





      return f'''{cls._gray}{s}{cls._reset}'''


def 					__SCREAMING_SNAKE_CASE  (							__lowercase:		List[List[Union[str, int]]]     ,							__lowercase:		List[str]):



  '''simple docstring'''






  __lowerCAmelCase			=				[max(len(str(__lowercase)) for x in col) for col in zip(*__lowercase     ,							__lowercase)]
  __lowerCAmelCase			=				('''{{:{}}} ''' * len(__lowercase)).format(*__lowercase)
  __lowerCAmelCase			=				[]
  lines.append(row_format.format(*__lowercase))
  lines.append(row_format.format(*['''-''' * w for w in col_widths]))
  for row in rows:
    lines.append(row_format.format(*__lowercase))
  return "\n".join(__lowercase)

class   __snake_case				:






    '''simple docstring'''





    def __init__(   self						:		List[str]			,						snake_case						:		List[str]							):

      """simple docstring"""





      __lowerCAmelCase			=				args


class   __snake_case				(			_a   ):






    '''simple docstring'''





    def 	A		(   self						:		List[Any]							):

      """simple docstring"""





      print(
          ANSI.red(
              '''ERROR! `huggingface-cli login` uses an outdated login mechanism '''
              '''that is not compatible with the Hugging Face Hub backend anymore. '''
              '''Please use `huggingface-cli login instead.'''							)							)


class   __snake_case				(			_a   ):






    '''simple docstring'''





    def 	A		(   self						:		int							):

      """simple docstring"""





      print(
          ANSI.red(
              '''WARNING! `transformers-cli whoami` is deprecated and will be removed in v5. Please use '''
              '''`huggingface-cli whoami` instead.'''							)							)
      __lowerCAmelCase			=				HfFolder.get_token()
      if token is None:
        print('''Not logged in'''							)
        exit()
      try:
        __lowerCAmelCase	,						__lowerCAmelCase			=				whoami(snake_case							)
        print(snake_case							)
        if orgs:
          print(ANSI.bold('''orgs: '''							)			,						''','''.join(snake_case							)							)
      except HTTPError as e:
        print(snake_case							)
        print(ANSI.red(e.response.text							)							)
        exit(1							)


class   __snake_case				(			_a   ):






    '''simple docstring'''





    def 	A		(   self						:		Any							):

      """simple docstring"""





      print(
          ANSI.red(
              '''ERROR! `transformers-cli logout` uses an outdated logout mechanism '''
              '''that is not compatible with the Hugging Face Hub backend anymore. '''
              '''Please use `huggingface-cli logout instead.'''							)							)


class   __snake_case				(			_a   ):






    '''simple docstring'''





    def 	A		(   self						:		Optional[int]							):

      """simple docstring"""





      print(
          ANSI.red(
              '''WARNING! Managing repositories through transformers-cli is deprecated. '''
              '''Please use `huggingface-cli` instead.'''							)							)
      __lowerCAmelCase			=				HfFolder.get_token()
      if token is None:
        print('''Not logged in'''							)
        exit(1							)
      try:
        __lowerCAmelCase			=				subprocess.check_output(['''git''', '''--version''']							).decode('''utf-8'''							)
        print(ANSI.gray(stdout.strip()							)							)
      except FileNotFoundError:
        print('''Looks like you do not have git installed, please install.'''							)

      try:
        __lowerCAmelCase			=				subprocess.check_output(['''git-lfs''', '''--version''']							).decode('''utf-8'''							)
        print(ANSI.gray(stdout.strip()							)							)
      except FileNotFoundError:
        print(
            ANSI.red(
                '''Looks like you do not have git-lfs installed, please install.'''
                ''' You can install from https://git-lfs.github.com/.'''
                ''' Then run `git lfs install` (you only have to do this once).'''							)							)
      print(''''''							)

      __lowerCAmelCase	,						__lowerCAmelCase			=				whoami(snake_case							)
      __lowerCAmelCase			=				self.args.organization if self.args.organization is not None else user
      __lowerCAmelCase			=				f'''{namespace}/{self.args.name}'''
      print(f'''You are about to create {ANSI.bold(snake_case							)}'''							)

      if not self.args.yes:
        __lowerCAmelCase			=				input('''Proceed? [Y/n] '''							).lower()
        if not (choice == "" or choice == "y" or choice == "yes"):
          print('''Abort'''							)
          exit()
      try:
        __lowerCAmelCase			=				create_repo(snake_case			,						name=self.args.name			,						organization=self.args.organization							)
      except HTTPError as e:
        print(snake_case							)
        print(ANSI.red(e.response.text							)							)
        exit(1							)
      print('''\nYour repo now lives at:'''							)
      print(f'''  {ANSI.bold(snake_case							)}'''							)
      print('''\nYou can clone it locally with the command below, and commit/push as usual.'''							)
      print(f'''\n  git clone {url}'''							)
      print(''''''							)
