





'''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_    :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_    :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 multiprocessing
import os
from typing import BinaryIO, Optional, Union

from .. import Dataset, Features, NamedSplit, config
from ..formatting import query_table
from ..packaged_modules.csv.csv import Csv
from ..utils import logging
from ..utils.typing import NestedDataStructureLike, PathLike
from .abc import AbstractDatasetReader
class    a_     (       _lowerCAmelCase							):





     def __init__(				self	:      Dict			,   lowercase	:      NestedDataStructureLike[PathLike]			,   lowercase	:      Optional[NamedSplit] = None			,   lowercase	:      Optional[Features] = None			,   lowercase	:      str = None			,   lowercase	:      bool = False			,   lowercase	:      bool = False			,   lowercase	:      Optional[int] = None			,   **lowercase	:      Any			,   ):





        """simple docstring"""




        super().__init__(
            lowercase			,   split=lowercase			,   features=lowercase			,   cache_dir=lowercase			,   keep_in_memory=lowercase			,   streaming=lowercase			,   num_proc=lowercase			,   **lowercase			,   )
        lowercase_    :Any					    =				path_or_paths if isinstance(lowercase			,   lowercase		) else {self.split: path_or_paths}
        lowercase_    :Any					    =				Csv(
            cache_dir=lowercase			,   data_files=lowercase			,   features=lowercase			,   **lowercase			,   )







     def 							lowercase__   (				self	:      Any		):





        """simple docstring"""




        if self.streaming:
           lowercase_    :Union[str, Any]					    =				self.builder.as_streaming_dataset(split=self.split		)
        # Build regular (map-style) dataset
        else:
           lowercase_    :Dict					    =				None
           lowercase_    :List[str]					    =				None
           lowercase_    :List[Any]					    =				None
           lowercase_    :Union[str, Any]					    =				None

           self.builder.download_and_prepare(
               download_config=lowercase			,   download_mode=lowercase			,   verification_mode=lowercase			,   base_path=lowercase			,   num_proc=self.num_proc			,   )
           lowercase_    :int					    =				self.builder.as_dataset(
               split=self.split			,   verification_mode=lowercase			,   in_memory=self.keep_in_memory		)
        return dataset







class    a_     :





     def __init__(				self	:      Dict			,   lowercase	:      Dataset			,   lowercase	:      Union[PathLike, BinaryIO]			,   lowercase	:      Optional[int] = None			,   lowercase	:      Optional[int] = None			,   **lowercase	:      Any			,   ):





        """simple docstring"""




        if num_proc is not None and num_proc <= 0:
           raise ValueError(F'num_proc {num_proc} must be an integer > 0.'		)

        lowercase_    :str					    =				dataset
        lowercase_    :List[Any]					    =				path_or_buf
        lowercase_    :Any					    =				batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE
        lowercase_    :int					    =				num_proc
        lowercase_    :Optional[Any]					    =				"utf-8"
        lowercase_    :Dict					    =				to_csv_kwargs





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





        """simple docstring"""




        lowercase_    :int					    =				self.to_csv_kwargs.pop("path_or_buf"			,   lowercase		)
        lowercase_    :List[str]					    =				self.to_csv_kwargs.pop("header"			,   lowercase		)
        lowercase_    :Optional[Any]					    =				self.to_csv_kwargs.pop("index"			,   lowercase		)

        if isinstance(self.path_or_buf			,   (str, bytes, os.PathLike)		):
           with open(self.path_or_buf			,   "wb+"		) as buffer:
              lowercase_    :List[Any]					    =				self._write(file_obj=lowercase			,   header=lowercase			,   index=lowercase			,   **self.to_csv_kwargs		)
        else:
           lowercase_    :Any					    =				self._write(file_obj=self.path_or_buf			,   header=lowercase			,   index=lowercase			,   **self.to_csv_kwargs		)
        return written





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





        """simple docstring"""




        lowercase_    ,							lowercase_    ,							lowercase_    ,							lowercase_    :Optional[Any]					    =				args

        lowercase_    :Dict					    =				query_table(
            table=self.dataset.data			,   key=slice(lowercase			,   offset + self.batch_size		)			,   indices=self.dataset._indices			,   )
        lowercase_    :List[str]					    =				batch.to_pandas().to_csv(
            path_or_buf=lowercase			,   header=header if (offset == 0) else False			,   index=lowercase			,   **lowercase		)
        return csv_str.encode(self.encoding		)







     def 							lowercase__   (				self	:      Dict			,   lowercase	:      BinaryIO			,   lowercase	:      Dict			,   lowercase	:      int			,   **lowercase	:      Any		):





        """simple docstring"""




        lowercase_    :Dict					    =				0

        if self.num_proc is None or self.num_proc == 1:
           for offset in logging.tqdm(
               range(0			,   len(self.dataset		)			,   self.batch_size		)			,   unit="ba"			,   disable=not logging.is_progress_bar_enabled()			,   desc="Creating CSV from Arrow format"			,   ):
              lowercase_    :Optional[Any]					    =				self._batch_csv((offset, header, index, to_csv_kwargs)		)
              written += file_obj.write(lowercase		)

        else:
           lowercase_    ,							lowercase_    :Optional[int]					    =				len(self.dataset		), self.batch_size
           with multiprocessing.Pool(self.num_proc		) as pool:
              for csv_str in logging.tqdm(
                  pool.imap(
                      self._batch_csv			,   [(offset, header, index, to_csv_kwargs) for offset in range(0			,   lowercase			,   lowercase		)]			,   )			,   total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size			,   unit="ba"			,   disable=not logging.is_progress_bar_enabled()			,   desc="Creating CSV from Arrow format"			,   ):
                 written += file_obj.write(lowercase		)

        return written


