





from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    get_image_size,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
      import PIL


__lowercase													=			logging.get_logger(__name__)

class   __snake_case				(			_a   ):






    '''simple docstring'''
    _lowerCAmelCase     =	["""pixel_values"""]





    def __init__(   self						:		List[Any]			,						snake_case						:		bool = True			,						snake_case						:		Dict[str, int] = None			,						snake_case						:		bool = True			,						snake_case						:		Dict[str, int] = None			,						snake_case						:		PILImageResampling = PILImageResampling.BICUBIC			,						snake_case						:		bool = True			,						snake_case						:		Union[int, float] = 1 / 255			,						snake_case						:		bool = True			,						snake_case						:		Optional[Union[float, List[float]]] = None			,						snake_case						:		Optional[Union[float, List[float]]] = None			,						**snake_case						:		Optional[Any]			,						):

      """simple docstring"""





      super().__init__(**snake_case							)
      __lowerCAmelCase			=				crop_size if crop_size is not None else {'''height''': 256, '''width''': 256}
      __lowerCAmelCase			=				get_size_dict(snake_case			,						param_name='''crop_size'''							)
      __lowerCAmelCase			=				size if size is not None else {'''height''': 224, '''width''': 224}
      __lowerCAmelCase			=				get_size_dict(snake_case							)

      __lowerCAmelCase			=				do_center_crop
      __lowerCAmelCase			=				crop_size
      __lowerCAmelCase			=				do_resize
      __lowerCAmelCase			=				size
      __lowerCAmelCase			=				resample
      __lowerCAmelCase			=				do_rescale
      __lowerCAmelCase			=				rescale_factor
      __lowerCAmelCase			=				do_normalize
      __lowerCAmelCase			=				image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
      __lowerCAmelCase			=				image_std if image_std is not None else IMAGENET_DEFAULT_STD





    def 	A		(   self						:		Optional[Any]			,						snake_case						:		np.ndarray			,						snake_case						:		Dict[str, int]			,						snake_case						:		Optional[int] = None			,						snake_case						:		Optional[Union[str, ChannelDimension]] = None			,						**snake_case						:		str			,						):

      """simple docstring"""





      __lowerCAmelCase			=				self.size if size is None else size
      __lowerCAmelCase			=				get_size_dict(snake_case							)
      __lowerCAmelCase			=				get_size_dict(snake_case			,						param_name='''crop_size'''							)

      __lowerCAmelCase	,						__lowerCAmelCase			=				get_image_size(snake_case							)
      __lowerCAmelCase			=				min(snake_case			,						snake_case							)
      __lowerCAmelCase			=				(size['''height'''] / crop_size['''height''']) * min_dim
      __lowerCAmelCase			=				(size['''width'''] / crop_size['''width''']) * min_dim
      return center_crop(snake_case			,						size=(cropped_height, cropped_width)			,						data_format=snake_case			,						**snake_case							)





    def 	A		(   self						:		List[str]			,						snake_case						:		np.ndarray			,						snake_case						:		Dict[str, int]			,						snake_case						:		PILImageResampling = PIL.Image.BICUBIC			,						snake_case						:		Optional[Union[str, ChannelDimension]] = None			,						**snake_case						:		List[str]			,						):

      """simple docstring"""





      __lowerCAmelCase			=				get_size_dict(snake_case							)
      if "height" not in size or "width" not in size:
        raise ValueError(f'''The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}'''							)
      return resize(
          snake_case			,						size=(size['''height'''], size['''width'''])			,						resample=snake_case			,						data_format=snake_case			,						**snake_case							)





    def 	A		(   self						:		List[Any]			,						snake_case						:		np.ndarray			,						snake_case						:		Union[int, float]			,						snake_case						:		Optional[Union[str, ChannelDimension]] = None			,						**snake_case						:		str			,						):

      """simple docstring"""





      return rescale(snake_case			,						scale=snake_case			,						data_format=snake_case			,						**snake_case							)





    def 	A		(   self						:		int			,						snake_case						:		np.ndarray			,						snake_case						:		Union[float, List[float]]			,						snake_case						:		Union[float, List[float]]			,						snake_case						:		Optional[Union[str, ChannelDimension]] = None			,						**snake_case						:		List[str]			,						):

      """simple docstring"""





      return normalize(snake_case			,						mean=snake_case			,						std=snake_case			,						data_format=snake_case			,						**snake_case							)





    def 	A		(   self						:		int			,						snake_case						:		ImageInput			,						snake_case						:		Optional[bool] = None			,						snake_case						:		Optional[Dict[str, int]] = None			,						snake_case						:		Optional[bool] = None			,						snake_case						:		Optional[Dict[str, int]] = None			,						snake_case						:		PILImageResampling = None			,						snake_case						:		Optional[bool] = None			,						snake_case						:		Optional[float] = None			,						snake_case						:		Optional[bool] = None			,						snake_case						:		Optional[Union[float, List[float]]] = None			,						snake_case						:		Optional[Union[float, List[float]]] = None			,						snake_case						:		Optional[Union[str, TensorType]] = None			,						snake_case						:		ChannelDimension = ChannelDimension.FIRST			,						**snake_case						:		Dict			,						):

      """simple docstring"""





      __lowerCAmelCase			=				do_center_crop if do_center_crop is not None else self.do_center_crop
      __lowerCAmelCase			=				crop_size if crop_size is not None else self.crop_size
      __lowerCAmelCase			=				get_size_dict(snake_case			,						param_name='''crop_size'''							)
      __lowerCAmelCase			=				do_resize if do_resize is not None else self.do_resize
      __lowerCAmelCase			=				size if size is not None else self.size
      __lowerCAmelCase			=				get_size_dict(snake_case							)
      __lowerCAmelCase			=				resample if resample is not None else self.resample
      __lowerCAmelCase			=				do_rescale if do_rescale is not None else self.do_rescale
      __lowerCAmelCase			=				rescale_factor if rescale_factor is not None else self.rescale_factor
      __lowerCAmelCase			=				do_normalize if do_normalize is not None else self.do_normalize
      __lowerCAmelCase			=				image_mean if image_mean is not None else self.image_mean
      __lowerCAmelCase			=				image_std if image_std is not None else self.image_std

      __lowerCAmelCase			=				make_list_of_images(snake_case							)

      if not valid_images(snake_case							):
        raise ValueError(
            '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
            '''torch.Tensor, tf.Tensor or jax.ndarray.'''							)

      if do_center_crop and crop_size is None:
        raise ValueError('''If `do_center_crop` is set to `True`, `crop_size` must be provided.'''							)

      if do_resize and size is None:
        raise ValueError('''Size must be specified if do_resize is True.'''							)

      if do_rescale and rescale_factor is None:
        raise ValueError('''Rescale factor must be specified if do_rescale is True.'''							)

      if do_normalize and (image_mean is None or image_std is None):
        raise ValueError('''Image mean and image standard deviation must be specified if do_normalize is True.'''							)

      # All transformations expect numpy arrays.
      __lowerCAmelCase			=				[to_numpy_array(snake_case							) for image in images]

      if do_center_crop:
        __lowerCAmelCase			=				[self.center_crop(snake_case			,						snake_case			,						size=snake_case							) for image in images]

      if do_resize:
        __lowerCAmelCase			=				[self.resize(image=snake_case			,						size=snake_case			,						resample=snake_case							) for image in images]

      if do_rescale:
        __lowerCAmelCase			=				[self.rescale(image=snake_case			,						scale=snake_case							) for image in images]

      if do_normalize:
        __lowerCAmelCase			=				[self.normalize(image=snake_case			,						mean=snake_case			,						std=snake_case							) for image in images]

      __lowerCAmelCase			=				[to_channel_dimension_format(snake_case			,						snake_case							) for image in images]

      __lowerCAmelCase			=				{'''pixel_values''': images}
      return BatchFeature(data=snake_case			,						tensor_type=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(''''''							)
