

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     lowerCamelCase_   ( _lowerCAmelCase):




	@staticmethod
	def 						a					( _UpperCAmelCase       ):
			__UpperCAmelCase  :     List[Any]		=    parser.add_parser('login'     ,     help='Log in using the same credentials as on huggingface.co'       )
			login_parser.set_defaults(func=lambda _UpperCAmelCase       : LoginCommand(_UpperCAmelCase       )       )
			__UpperCAmelCase  :     List[Any]		=    parser.add_parser('whoami'     ,     help='Find out which huggingface.co account you are logged in as.'       )
			whoami_parser.set_defaults(func=lambda _UpperCAmelCase       : WhoamiCommand(_UpperCAmelCase       )       )
			__UpperCAmelCase  :     List[str]		=    parser.add_parser('logout'     ,     help='Log out'       )
			logout_parser.set_defaults(func=lambda _UpperCAmelCase       : LogoutCommand(_UpperCAmelCase       )       )

			# new system: git-based repo system
			__UpperCAmelCase  :     str		=    parser.add_parser(
			    'repo'     ,     help='Deprecated: use `huggingface-cli` instead. Commands to interact with your huggingface.co repos.'     ,     )
			__UpperCAmelCase  :     Any		=    repo_parser.add_subparsers(
			    help='Deprecated: use `huggingface-cli` instead. huggingface.co repos related commands'       )
			__UpperCAmelCase  :     Union[str, Any]		=    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=_UpperCAmelCase     ,     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=_UpperCAmelCase     ,     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 _UpperCAmelCase       : RepoCreateCommand(_UpperCAmelCase       )       )



class     lowerCamelCase_   :
	_lowerCAmelCase       		=  '''\u001b[1m'''
	_lowerCAmelCase       		=  '''\u001b[31m'''
	_lowerCAmelCase       		=  '''\u001b[90m'''
	_lowerCAmelCase       		=  '''\u001b[0m'''




	@classmethod
	def 						a					( cls     ,     _UpperCAmelCase       ):
			return F"{cls._bold}{s}{cls._reset}"




	@classmethod
	def 						a					( cls     ,     _UpperCAmelCase       ):
			return F"{cls._bold}{cls._red}{s}{cls._reset}"




	@classmethod
	def 						a					( cls     ,     _UpperCAmelCase       ):
			return F"{cls._gray}{s}{cls._reset}"





def    _snake_case		(snake_case_				:    List[List[Union[str, int]]]						,					snake_case_				:    List[str]     )       ->		str:
		__UpperCAmelCase  :     Dict		=    [max(len(str(snake_case_     )     ) for x in col     ) for col in zip(*snake_case_						,					snake_case_     )]
		__UpperCAmelCase  :     Optional[Any]		=    ('{{:{}}} ' * len(snake_case_     )).format(*snake_case_     )
		__UpperCAmelCase  :     List[str]		=    []
		lines.append(row_format.format(*snake_case_     )     )
		lines.append(row_format.format(*['-' * w for w in col_widths]     )     )
		for row in rows:
				lines.append(row_format.format(*snake_case_     )     )
		return "\n".join(snake_case_     )


class     lowerCamelCase_   :




	def __init__( self     ,     _UpperCAmelCase       ):
			__UpperCAmelCase  :     List[Any]		=    args



class     lowerCamelCase_   ( _lowerCAmelCase):




	def 						a					( self       ):
			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     lowerCamelCase_   ( _lowerCAmelCase):




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



class     lowerCamelCase_   ( _lowerCAmelCase):




	def 						a					( self       ):
			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     lowerCamelCase_   ( _lowerCAmelCase):




	def 						a					( self       ):
			print(
			    ANSI.red(
			        'WARNING! Managing repositories through transformers-cli is deprecated. '
			        'Please use `huggingface-cli` instead.'       )       )
			__UpperCAmelCase  :     str		=    HfFolder.get_token()
			if token is None:
					print('Not logged in'       )
					exit(1       )
			try:
					__UpperCAmelCase  :     List[Any]		=    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:
					__UpperCAmelCase  :     Union[str, Any]		=    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(''       )

			__UpperCAmelCase  :     Tuple		=    whoami(_UpperCAmelCase       )
			__UpperCAmelCase  :     Any		=    self.args.organization if self.args.organization is not None else user
			__UpperCAmelCase  :     Any		=    F"{namespace}/{self.args.name}"
			print(F"You are about to create {ANSI.bold(_UpperCAmelCase       )}"       )

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








import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionDualGuidedPipeline
from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device


_SCREAMING_SNAKE_CASE          = False


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




 def 						a					( self       ):
   # clean up the VRAM after each test
   super().tearDown()
   gc.collect()
   torch.cuda.empty_cache()




 def 						a					( self       ):
   __UpperCAmelCase  :     Dict		=    VersatileDiffusionDualGuidedPipeline.from_pretrained('shi-labs/versatile-diffusion'       )
   # remove text_unet
   pipe.remove_unused_weights()
   pipe.to(_UpperCAmelCase       )
   pipe.set_progress_bar_config(disable=_UpperCAmelCase       )

   __UpperCAmelCase  :     Any		=    load_image(
       'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg'       )

   __UpperCAmelCase  :     Optional[Any]		=    torch.manual_seed(0       )
   __UpperCAmelCase  :     Union[str, Any]		=    pipe(
       prompt='first prompt'     ,     image=_UpperCAmelCase     ,     text_to_image_strength=0.7_5     ,     generator=_UpperCAmelCase     ,     guidance_scale=7.5     ,     num_inference_steps=2     ,     output_type='numpy'     ,     ).images

   with tempfile.TemporaryDirectory() as tmpdirname:
     pipe.save_pretrained(_UpperCAmelCase       )
     __UpperCAmelCase  :     List[str]		=    VersatileDiffusionDualGuidedPipeline.from_pretrained(_UpperCAmelCase       )

   pipe.to(_UpperCAmelCase       )
   pipe.set_progress_bar_config(disable=_UpperCAmelCase       )

   __UpperCAmelCase  :     List[str]		=    generator.manual_seed(0       )
   __UpperCAmelCase  :     Optional[int]		=    pipe(
       prompt='first prompt'     ,     image=_UpperCAmelCase     ,     text_to_image_strength=0.7_5     ,     generator=_UpperCAmelCase     ,     guidance_scale=7.5     ,     num_inference_steps=2     ,     output_type='numpy'     ,     ).images

   assert np.abs(image - new_image       ).sum() < 1E-5, "Models don't have the same forward pass"




 def 						a					( self       ):
   __UpperCAmelCase  :     Optional[Any]		=    VersatileDiffusionDualGuidedPipeline.from_pretrained('shi-labs/versatile-diffusion'       )
   pipe.remove_unused_weights()
   pipe.to(_UpperCAmelCase       )
   pipe.set_progress_bar_config(disable=_UpperCAmelCase       )

   __UpperCAmelCase  :     Tuple		=    'cyberpunk 2077'
   __UpperCAmelCase  :     Dict		=    load_image(
       'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg'       )
   __UpperCAmelCase  :     Optional[Any]		=    torch.manual_seed(0       )
   __UpperCAmelCase  :     List[Any]		=    pipe(
       prompt=_UpperCAmelCase     ,     image=_UpperCAmelCase     ,     text_to_image_strength=0.7_5     ,     generator=_UpperCAmelCase     ,     guidance_scale=7.5     ,     num_inference_steps=50     ,     output_type='numpy'     ,     ).images

   __UpperCAmelCase  :     Tuple		=    image[0, 253:256, 253:256, -1]

   assert image.shape == (1, 512, 512, 3)
   __UpperCAmelCase  :     Tuple		=    np.array([0.0_7_8_7, 0.0_8_4_9, 0.0_8_2_6, 0.0_8_1_2, 0.0_8_0_7, 0.0_7_9_5, 0.0_8_1_8, 0.0_7_9_8, 0.0_7_7_9]       )

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





