
"""simple docstring"""


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 					A_			(  SCREAMING_SNAKE_CASE__     ):



							"""simple docstring"""






							@staticmethod
							def    UpperCAmelCase__							(						lowerCamelCase_						:List[Any] ):





										"""simple docstring"""

										lowerCamelCase__			:  List[str]  =parser.add_parser('login'  ,							help='Log in using the same credentials as on huggingface.co' )
										login_parser.set_defaults(func=lambda lowerCamelCase_ : LoginCommand(lowerCamelCase_ ) )
										lowerCamelCase__			:  Dict  =parser.add_parser('whoami'  ,							help='Find out which huggingface.co account you are logged in as.' )
										whoami_parser.set_defaults(func=lambda lowerCamelCase_ : WhoamiCommand(lowerCamelCase_ ) )
										lowerCamelCase__			:  Optional[int]  =parser.add_parser('logout'  ,							help='Log out' )
										logout_parser.set_defaults(func=lambda lowerCamelCase_ : LogoutCommand(lowerCamelCase_ ) )

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






class 					A_			:



							"""simple docstring"""






							SCREAMING_SNAKE_CASE_			   =     """\u001b[1m"""
							SCREAMING_SNAKE_CASE_			   =     """\u001b[31m"""
							SCREAMING_SNAKE_CASE_			   =     """\u001b[90m"""
							SCREAMING_SNAKE_CASE_			   =     """\u001b[0m"""





							@classmethod
							def    UpperCAmelCase__							(						cls						:List[str]  ,							lowerCamelCase_						:Any ):





										"""simple docstring"""

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





							@classmethod
							def    UpperCAmelCase__							(						cls						:Tuple  ,							lowerCamelCase_						:List[str] ):





										"""simple docstring"""

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





							@classmethod
							def    UpperCAmelCase__							(						cls						:Union[str, Any]  ,							lowerCamelCase_						:int ):





										"""simple docstring"""

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






def      lowerCAmelCase_     (	snake_case_	:    Optional[Any]							,					snake_case_	:    Union[str, Any]    )     ->str:
			lowerCamelCase__			:  List[Any]  =[max(len(str(snake_case_    )    ) for x in col    ) for col in zip(*snake_case_							,					snake_case_    )]
			lowerCamelCase__			:  Dict  =('{{:{}}} ' * len(snake_case_    )).format(*snake_case_    )
			lowerCamelCase__			:  Tuple  =[]
			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 					A_			:



							"""simple docstring"""






							def __init__(						self						:Dict  ,							lowerCamelCase_						:str ):





										"""simple docstring"""

										lowerCamelCase__			:  Dict  =args






class 					A_			(  SCREAMING_SNAKE_CASE__     ):



							"""simple docstring"""






							def    UpperCAmelCase__							(						self						:List[str] ):





										"""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 					A_			(  SCREAMING_SNAKE_CASE__     ):



							"""simple docstring"""






							def    UpperCAmelCase__							(						self						:Tuple ):





										"""simple docstring"""

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






class 					A_			(  SCREAMING_SNAKE_CASE__     ):



							"""simple docstring"""






							def    UpperCAmelCase__							(						self						:Tuple ):





										"""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 					A_			(  SCREAMING_SNAKE_CASE__     ):



							"""simple docstring"""






							def    UpperCAmelCase__							(						self						:Union[str, Any] ):





										"""simple docstring"""

										print(
										    ANSI.red(
										        'WARNING! Managing repositories through transformers-cli is deprecated. '
										        'Please use `huggingface-cli` instead.' ) )
										lowerCamelCase__			:  Optional[Any]  =HfFolder.get_token()
										if token is None:
													print('Not logged in' )
													exit(1 )
										try:
													lowerCamelCase__			:  int  =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__			:  int  =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__			:  Optional[Any]  =whoami(lowerCamelCase_ )
										lowerCamelCase__			:  Union[str, Any]  =self.args.organization if self.args.organization is not None else user
										lowerCamelCase__			:  Optional[int]  =f"""{namespace}/{self.args.name}"""
										print(f"""You are about to create {ANSI.bold(lowerCamelCase_ )}""" )

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

"""simple docstring"""


from typing import Any, Callable, Dict, List, Optional, Union

import PIL.Image
import torch
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    LMSDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionImgaImgPipeline,
    StableDiffusionInpaintPipelineLegacy,
    StableDiffusionPipeline,
    UNetaDConditionModel,
)
from diffusers.configuration_utils import FrozenDict
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.utils import deprecate, logging


lowerCAmelCase			=		logging.get_logger(__name__)  # pylint: disable=invalid-name

class 					A_			(  A__     ):



							"""simple docstring"""






							SCREAMING_SNAKE_CASE_			   =     ["""safety_checker""", """feature_extractor"""]





							def __init__(						self						:Optional[Any]  ,							lowerCamelCase_						:AutoencoderKL  ,							lowerCamelCase_						:CLIPTextModel  ,							lowerCamelCase_						:CLIPTokenizer  ,							lowerCamelCase_						:UNetaDConditionModel  ,							lowerCamelCase_						:Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]  ,							lowerCamelCase_						:StableDiffusionSafetyChecker  ,							lowerCamelCase_						:CLIPImageProcessor  ,							lowerCamelCase_						:bool = True  ,							):





										"""simple docstring"""

										super().__init__()
										if hasattr(scheduler.config  ,							'steps_offset' ) and scheduler.config.steps_offset != 1:
													lowerCamelCase__			:  Dict  =(
													    f"""The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"""
													    f""" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure """
													    'to update the config accordingly as leaving `steps_offset` might led to incorrect results'
													    ' in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,'
													    ' it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`'
													    ' file'
													)
													deprecate('steps_offset!=1'  ,							'1.0.0'  ,							lowerCamelCase_  ,							standard_warn=lowerCamelCase_ )
													lowerCamelCase__			:  Tuple  =dict(scheduler.config )
													lowerCamelCase__			:  str  =1
													lowerCamelCase__			:  List[Any]  =FrozenDict(lowerCamelCase_ )

										self.register_modules(
										    vae=lowerCamelCase_  ,							text_encoder=lowerCamelCase_  ,							tokenizer=lowerCamelCase_  ,							unet=lowerCamelCase_  ,							scheduler=lowerCamelCase_  ,							safety_checker=lowerCamelCase_  ,							feature_extractor=lowerCamelCase_  ,							)
										self.register_to_config(requires_safety_checker=lowerCamelCase_ )





							@property
							def    UpperCAmelCase__							(						self						:Any ):





										"""simple docstring"""

										return {k: getattr(self  ,							lowerCamelCase_ ) for k in self.config.keys() if not k.startswith('_' )}





							def    UpperCAmelCase__							(						self						:Optional[Any]  ,							lowerCamelCase_						:Optional[Union[str, int]] = "auto" ):





										"""simple docstring"""

										if slice_size == "auto":
													# half the attention head size is usually a good trade-off between
													# speed and memory
													lowerCamelCase__			:  List[Any]  =self.unet.config.attention_head_dim // 2
										self.unet.set_attention_slice(lowerCamelCase_ )





							def    UpperCAmelCase__							(						self						:Any ):





										"""simple docstring"""

										self.enable_attention_slicing(lowerCamelCase_ )





							@torch.no_grad()
							def    UpperCAmelCase__							(						self						:Optional[int]  ,							lowerCamelCase_						:Union[str, List[str]]  ,							lowerCamelCase_						:Union[torch.FloatTensor, PIL.Image.Image]  ,							lowerCamelCase_						:Union[torch.FloatTensor, PIL.Image.Image]  ,							lowerCamelCase_						:float = 0.8  ,							lowerCamelCase_						:Optional[int] = 50  ,							lowerCamelCase_						:Optional[float] = 7.5  ,							lowerCamelCase_						:Optional[Union[str, List[str]]] = None  ,							lowerCamelCase_						:Optional[int] = 1  ,							lowerCamelCase_						:Optional[float] = 0.0  ,							lowerCamelCase_						:Optional[torch.Generator] = None  ,							lowerCamelCase_						:Optional[str] = "pil"  ,							lowerCamelCase_						:bool = True  ,							lowerCamelCase_						:Optional[Callable[[int, int, torch.FloatTensor], None]] = None  ,							lowerCamelCase_						:int = 1  ,							):





										"""simple docstring"""

										return StableDiffusionInpaintPipelineLegacy(**self.components )(
										    prompt=lowerCamelCase_  ,							image=lowerCamelCase_  ,							mask_image=lowerCamelCase_  ,							strength=lowerCamelCase_  ,							num_inference_steps=lowerCamelCase_  ,							guidance_scale=lowerCamelCase_  ,							negative_prompt=lowerCamelCase_  ,							num_images_per_prompt=lowerCamelCase_  ,							eta=lowerCamelCase_  ,							generator=lowerCamelCase_  ,							output_type=lowerCamelCase_  ,							return_dict=lowerCamelCase_  ,							callback=lowerCamelCase_  ,							)





							@torch.no_grad()
							def    UpperCAmelCase__							(						self						:Any  ,							lowerCamelCase_						:Union[str, List[str]]  ,							lowerCamelCase_						:Union[torch.FloatTensor, PIL.Image.Image]  ,							lowerCamelCase_						:float = 0.8  ,							lowerCamelCase_						:Optional[int] = 50  ,							lowerCamelCase_						:Optional[float] = 7.5  ,							lowerCamelCase_						:Optional[Union[str, List[str]]] = None  ,							lowerCamelCase_						:Optional[int] = 1  ,							lowerCamelCase_						:Optional[float] = 0.0  ,							lowerCamelCase_						:Optional[torch.Generator] = None  ,							lowerCamelCase_						:Optional[str] = "pil"  ,							lowerCamelCase_						:bool = True  ,							lowerCamelCase_						:Optional[Callable[[int, int, torch.FloatTensor], None]] = None  ,							lowerCamelCase_						:int = 1  ,							**lowerCamelCase_						:str  ,							):





										"""simple docstring"""

										return StableDiffusionImgaImgPipeline(**self.components )(
										    prompt=lowerCamelCase_  ,							image=lowerCamelCase_  ,							strength=lowerCamelCase_  ,							num_inference_steps=lowerCamelCase_  ,							guidance_scale=lowerCamelCase_  ,							negative_prompt=lowerCamelCase_  ,							num_images_per_prompt=lowerCamelCase_  ,							eta=lowerCamelCase_  ,							generator=lowerCamelCase_  ,							output_type=lowerCamelCase_  ,							return_dict=lowerCamelCase_  ,							callback=lowerCamelCase_  ,							callback_steps=lowerCamelCase_  ,							)





							@torch.no_grad()
							def    UpperCAmelCase__							(						self						:Optional[int]  ,							lowerCamelCase_						:Union[str, List[str]]  ,							lowerCamelCase_						:int = 512  ,							lowerCamelCase_						:int = 512  ,							lowerCamelCase_						:int = 50  ,							lowerCamelCase_						:float = 7.5  ,							lowerCamelCase_						:Optional[Union[str, List[str]]] = None  ,							lowerCamelCase_						:Optional[int] = 1  ,							lowerCamelCase_						:float = 0.0  ,							lowerCamelCase_						:Optional[torch.Generator] = None  ,							lowerCamelCase_						:Optional[torch.FloatTensor] = None  ,							lowerCamelCase_						:Optional[str] = "pil"  ,							lowerCamelCase_						:bool = True  ,							lowerCamelCase_						:Optional[Callable[[int, int, torch.FloatTensor], None]] = None  ,							lowerCamelCase_						:int = 1  ,							):





										"""simple docstring"""

										return StableDiffusionPipeline(**self.components )(
										    prompt=lowerCamelCase_  ,							height=lowerCamelCase_  ,							width=lowerCamelCase_  ,							num_inference_steps=lowerCamelCase_  ,							guidance_scale=lowerCamelCase_  ,							negative_prompt=lowerCamelCase_  ,							num_images_per_prompt=lowerCamelCase_  ,							eta=lowerCamelCase_  ,							generator=lowerCamelCase_  ,							latents=lowerCamelCase_  ,							output_type=lowerCamelCase_  ,							return_dict=lowerCamelCase_  ,							callback=lowerCamelCase_  ,							callback_steps=lowerCamelCase_  ,							)