





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





     @staticmethod
     def 							lowercase__   (				lowercase	:      ArgumentParser		):





        """simple docstring"""




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

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







class    a_     :
     __A  				=    "\u001b[1m"
     __A  				=    "\u001b[31m"
     __A  				=    "\u001b[90m"
     __A  				=    "\u001b[0m"





     @classmethod
     def 							lowercase__   (				cls	:      Union[str, Any]			,   lowercase	:      List[Any]		):





        """simple docstring"""




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





     @classmethod
     def 							lowercase__   (				cls	:      Optional[int]			,   lowercase	:      Optional[int]		):





        """simple docstring"""




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







     @classmethod
     def 							lowercase__   (				cls	:      Optional[int]			,   lowercase	:      List[Any]		):





        """simple docstring"""




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







def 							UpperCAmelCase_						(		__lowerCamelCase      :      List[List[Union[str, int]]]			,__lowerCamelCase      :      List[str]				):
   lowercase_    :List[str]					    =				[max(len(str(__lowerCamelCase				)				) for x in col				) for col in zip(*__lowerCamelCase			,__lowerCamelCase				)]
   lowercase_    :Any					    =				("{{:{}}} " * len(__lowerCamelCase				)).format(*__lowerCamelCase				)
   lowercase_    :Tuple					    =				[]
   lines.append(row_format.format(*__lowerCamelCase				)				)
   lines.append(row_format.format(*["-" * w for w in col_widths]				)				)
   for row in rows:
      lines.append(row_format.format(*__lowerCamelCase				)				)
   return "\n".join(__lowerCamelCase				)
class    a_     :





     def __init__(				self	:      Union[str, Any]			,   lowercase	:      str		):





        """simple docstring"""




        lowercase_    :List[str]					    =				args







class    a_     (       _lowerCAmelCase							):





     def 							lowercase__   (				self	:      int		):





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





     def 							lowercase__   (				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."		)		)
        lowercase_    :List[str]					    =				HfFolder.get_token()
        if token is None:
           print("Not logged in"		)
           exit()
        try:
           lowercase_    ,							lowercase_    :Union[str, Any]					    =				whoami(lowercase		)
           print(lowercase		)
           if orgs:
              print(ANSI.bold("orgs: "		)			,   ",".join(lowercase		)		)
        except HTTPError as e:
           print(lowercase		)
           print(ANSI.red(e.response.text		)		)
           exit(1		)







class    a_     (       _lowerCAmelCase							):





     def 							lowercase__   (				self	:      Optional[int]		):





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





     def 							lowercase__   (				self	:      List[Any]		):





        """simple docstring"""




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

        lowercase_    ,							lowercase_    :List[Any]					    =				whoami(lowercase		)
        lowercase_    :Union[str, Any]					    =				self.args.organization if self.args.organization is not None else user
        lowercase_    :List[Any]					    =				F'{namespace}/{self.args.name}'
        print(F'You are about to create {ANSI.bold(lowercase		)}'		)

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









'''simple docstring'''


import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
 import torch

if is_vision_available():
 from PIL import Image

 from transformers import EfficientNetImageProcessor
class    a_     (       unittest.TestCase							):





     def __init__(				self	:      int			,   lowercase	:      Optional[int]			,   lowercase	:      Tuple=13			,   lowercase	:      str=3			,   lowercase	:      List[str]=18			,   lowercase	:      Union[str, Any]=30			,   lowercase	:      Any=400			,   lowercase	:      Tuple=True			,   lowercase	:      Union[str, Any]=None			,   lowercase	:      Optional[Any]=True			,   lowercase	:      Optional[int]=[0.5, 0.5, 0.5]			,   lowercase	:      List[str]=[0.5, 0.5, 0.5]			,   ):





        """simple docstring"""




        lowercase_    :Dict					    =				size if size is not None else {"height": 18, "width": 18}
        lowercase_    :Optional[Any]					    =				parent
        lowercase_    :str					    =				batch_size
        lowercase_    :Optional[int]					    =				num_channels
        lowercase_    :str					    =				image_size
        lowercase_    :Tuple					    =				min_resolution
        lowercase_    :Optional[Any]					    =				max_resolution
        lowercase_    :List[str]					    =				do_resize
        lowercase_    :Optional[Any]					    =				size
        lowercase_    :Optional[int]					    =				do_normalize
        lowercase_    :Union[str, Any]					    =				image_mean
        lowercase_    :Dict					    =				image_std







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





        """simple docstring"""




        return {
            "image_mean": self.image_mean,
            "image_std": self.image_std,
            "do_normalize": self.do_normalize,
            "do_resize": self.do_resize,
            "size": self.size,
        }







@require_torch
@require_vision
class    a_     (       _lowerCAmelCase			,		unittest.TestCase							):
     __A  				=    EfficientNetImageProcessor if is_vision_available() else None





     def 							lowercase__   (				self	:      Optional[int]		):





        """simple docstring"""




        lowercase_    :List[Any]					    =				EfficientNetImageProcessorTester(self		)





     @property
     def 							lowercase__   (				self	:      Optional[Any]		):





        """simple docstring"""




        return self.image_processor_tester.prepare_image_processor_dict()





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





        """simple docstring"""




        lowercase_    :Optional[Any]					    =				self.image_processing_class(**self.image_processor_dict		)
        self.assertTrue(hasattr(lowercase			,   "image_mean"		)		)
        self.assertTrue(hasattr(lowercase			,   "image_std"		)		)
        self.assertTrue(hasattr(lowercase			,   "do_normalize"		)		)
        self.assertTrue(hasattr(lowercase			,   "do_resize"		)		)
        self.assertTrue(hasattr(lowercase			,   "size"		)		)





     def 							lowercase__   (				self	:      str		):





        """simple docstring"""




        lowercase_    :Tuple					    =				self.image_processing_class.from_dict(self.image_processor_dict		)
        self.assertEqual(image_processor.size			,   {"height": 18, "width": 18}		)

        lowercase_    :List[str]					    =				self.image_processing_class.from_dict(self.image_processor_dict			,   size=42		)
        self.assertEqual(image_processor.size			,   {"height": 42, "width": 42}		)





     def 							lowercase__   (				self	:      Optional[int]		):





        """simple docstring"""




        lowercase_    :List[Any]					    =				self.image_processing_class(**self.image_processor_dict		)
        # create random PIL images
        lowercase_    :Tuple					    =				prepare_image_inputs(self.image_processor_tester			,   equal_resolution=lowercase		)
        for image in image_inputs:
           self.assertIsInstance(lowercase			,   Image.Image		)

        # Test not batched input
        lowercase_    :Optional[Any]					    =				image_processing(image_inputs[0]			,   return_tensors="pt"		).pixel_values
        self.assertEqual(
            encoded_images.shape			,   (
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["height"],
                self.image_processor_tester.size["width"],
            )			,   )

        # Test batched
        lowercase_    :Optional[Any]					    =				image_processing(lowercase			,   return_tensors="pt"		).pixel_values
        self.assertEqual(
            encoded_images.shape			,   (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["height"],
                self.image_processor_tester.size["width"],
            )			,   )





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





        """simple docstring"""




        lowercase_    :int					    =				self.image_processing_class(**self.image_processor_dict		)
        # create random numpy tensors
        lowercase_    :List[Any]					    =				prepare_image_inputs(self.image_processor_tester			,   equal_resolution=lowercase			,   numpify=lowercase		)
        for image in image_inputs:
           self.assertIsInstance(lowercase			,   np.ndarray		)

        # Test not batched input
        lowercase_    :Optional[Any]					    =				image_processing(image_inputs[0]			,   return_tensors="pt"		).pixel_values
        self.assertEqual(
            encoded_images.shape			,   (
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["height"],
                self.image_processor_tester.size["width"],
            )			,   )

        # Test batched
        lowercase_    :Any					    =				image_processing(lowercase			,   return_tensors="pt"		).pixel_values
        self.assertEqual(
            encoded_images.shape			,   (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["height"],
                self.image_processor_tester.size["width"],
            )			,   )







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





        """simple docstring"""




        lowercase_    :str					    =				self.image_processing_class(**self.image_processor_dict		)
        # create random PyTorch tensors
        lowercase_    :Tuple					    =				prepare_image_inputs(self.image_processor_tester			,   equal_resolution=lowercase			,   torchify=lowercase		)
        for image in image_inputs:
           self.assertIsInstance(lowercase			,   torch.Tensor		)

        # Test not batched input
        lowercase_    :str					    =				image_processing(image_inputs[0]			,   return_tensors="pt"		).pixel_values
        self.assertEqual(
            encoded_images.shape			,   (
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["height"],
                self.image_processor_tester.size["width"],
            )			,   )

        # Test batched
        lowercase_    :Optional[int]					    =				image_processing(lowercase			,   return_tensors="pt"		).pixel_values
        self.assertEqual(
            encoded_images.shape			,   (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["height"],
                self.image_processor_tester.size["width"],
            )			,   )


