


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





   @staticmethod
   def 		UpperCamelCase_     (       SCREAMING_SNAKE_CASE)     ->     Dict:
      _lowerCamelCase  :				Optional[Any]      =		parser.add_parser("""login"""			,      help="""Log in using the same credentials as on huggingface.co""")
      login_parser.set_defaults(func=lambda SCREAMING_SNAKE_CASE: LoginCommand(SCREAMING_SNAKE_CASE))
      _lowerCamelCase  :				Any      =		parser.add_parser("""whoami"""			,      help="""Find out which huggingface.co account you are logged in as.""")
      whoami_parser.set_defaults(func=lambda SCREAMING_SNAKE_CASE: WhoamiCommand(SCREAMING_SNAKE_CASE))
      _lowerCamelCase  :				Optional[int]      =		parser.add_parser("""logout"""			,      help="""Log out""")
      logout_parser.set_defaults(func=lambda SCREAMING_SNAKE_CASE: LogoutCommand(SCREAMING_SNAKE_CASE))

      # 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  :				Optional[Any]      =		repo_parser.add_subparsers(
          help="""Deprecated: use `huggingface-cli` instead. huggingface.co repos related commands""")
      _lowerCamelCase  :				Dict      =		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=SCREAMING_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=SCREAMING_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 SCREAMING_SNAKE_CASE: RepoCreateCommand(SCREAMING_SNAKE_CASE))







class   lowercase__							:
   __UpperCAmelCase       					=				'''\u001b[1m'''
   __UpperCAmelCase       					=				'''\u001b[31m'''
   __UpperCAmelCase       					=				'''\u001b[90m'''
   __UpperCAmelCase       					=				'''\u001b[0m'''





   @classmethod
   def 		UpperCamelCase_     (       cls			,      SCREAMING_SNAKE_CASE)     ->     Dict:
      return F'{cls._bold}{s}{cls._reset}'





   @classmethod
   def 		UpperCamelCase_     (       cls			,      SCREAMING_SNAKE_CASE)     ->     Union[str, Any]:
      return F'{cls._bold}{cls._red}{s}{cls._reset}'





   @classmethod
   def 		UpperCamelCase_     (       cls			,      SCREAMING_SNAKE_CASE)     ->     Tuple:
      return F'{cls._gray}{s}{cls._reset}'







def 							_snake_case			(      __snake_case       :			List[List[Union[str, int]]]	,   __snake_case       :			List[str]      ):




   """simple docstring"""







   _lowerCamelCase  :				str      =		[max(len(str(__snake_case      )      ) for x in col      ) for col in zip(*__snake_case	,   __snake_case      )]
   _lowerCamelCase  :				Any      =		("""{{:{}}} """ * len(__snake_case      )).format(*__snake_case      )
   _lowerCamelCase  :				Optional[Any]      =		[]
   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   lowercase__							:





   def __init__(       self			,      SCREAMING_SNAKE_CASE)     ->     List[str]:
      _lowerCamelCase  :				Any      =		args







class   lowercase__							(				A_							):





   def 		UpperCamelCase_     (       self)     ->     int:
      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   lowercase__							(				A_							):





   def 		UpperCamelCase_     (       self)     ->     Tuple:
      print(
          ANSI.red(
              """WARNING! `transformers-cli whoami` is deprecated and will be removed in v5. Please use """
              """`huggingface-cli whoami` instead."""))
      _lowerCamelCase  :				Tuple      =		HfFolder.get_token()
      if token is None:
         print("""Not logged in""")
         exit()
      try:
         _lowerCamelCase      ,						_lowerCamelCase  :				int      =		whoami(SCREAMING_SNAKE_CASE)
         print(SCREAMING_SNAKE_CASE)
         if orgs:
            print(ANSI.bold("""orgs: """)			,      """,""".join(SCREAMING_SNAKE_CASE))
      except HTTPError as e:
         print(SCREAMING_SNAKE_CASE)
         print(ANSI.red(e.response.text))
         exit(1)







class   lowercase__							(				A_							):





   def 		UpperCamelCase_     (       self)     ->     Union[str, Any]:
      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   lowercase__							(				A_							):





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

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

      if not self.args.yes:
         _lowerCamelCase  :				Tuple      =		input("""Proceed? [Y/n] """).lower()
         if not (choice == "" or choice == "y" or choice == "yes"):
            print("""Abort""")
            exit()
      try:
         _lowerCamelCase  :				int      =		create_repo(SCREAMING_SNAKE_CASE			,      name=self.args.name			,      organization=self.args.organization)
      except HTTPError as e:
         print(SCREAMING_SNAKE_CASE)
         print(ANSI.red(e.response.text))
         exit(1)
      print("""\nYour repo now lives at:""")
      print(F'  {ANSI.bold(SCREAMING_SNAKE_CASE)}')
      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 itertools
from dataclasses import dataclass
from io import StringIO
from typing import Optional

import pyarrow as pa

import datasets
from datasets.features.features import require_storage_cast
from datasets.table import table_cast


UpperCAmelCase   =	datasets.utils.logging.get_logger(__name__)




@dataclass
class   lowercase__							(				datasets.BuilderConfig							):
   __UpperCAmelCase       					=				None
   __UpperCAmelCase       					=				"utf-8"
   __UpperCAmelCase       					=				None
   __UpperCAmelCase       					=				10 << 20  # 10MB
   __UpperCAmelCase       					=				False
   __UpperCAmelCase       					=				"line"







class   lowercase__							(				datasets.ArrowBasedBuilder							):
   __UpperCAmelCase       					=				TextConfig





   def 		UpperCamelCase_     (       self)     ->     int:
      return datasets.DatasetInfo(features=self.config.features)





   def 		UpperCamelCase_     (       self			,      SCREAMING_SNAKE_CASE)     ->     Optional[int]:
      if not self.config.data_files:
         raise ValueError(F'At least one data file must be specified, but got data_files={self.config.data_files}')
      _lowerCamelCase  :				Dict      =		dl_manager.download_and_extract(self.config.data_files)
      if isinstance(SCREAMING_SNAKE_CASE			,      (str, list, tuple)):
         _lowerCamelCase  :				Optional[Any]      =		data_files
         if isinstance(SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE):
            _lowerCamelCase  :				List[Any]      =		[files]
         _lowerCamelCase  :				List[str]      =		[dl_manager.iter_files(SCREAMING_SNAKE_CASE) for file in files]
         return [datasets.SplitGenerator(name=datasets.Split.TRAIN			,      gen_kwargs={"""files""": files})]
      _lowerCamelCase  :				int      =		[]
      for split_name, files in data_files.items():
         if isinstance(SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE):
            _lowerCamelCase  :				Any      =		[files]
         _lowerCamelCase  :				Any      =		[dl_manager.iter_files(SCREAMING_SNAKE_CASE) for file in files]
         splits.append(datasets.SplitGenerator(name=SCREAMING_SNAKE_CASE			,      gen_kwargs={"""files""": files}))
      return splits





   def 		UpperCamelCase_     (       self			,      SCREAMING_SNAKE_CASE)     ->     pa.Table:
      if self.config.features is not None:
         _lowerCamelCase  :				Union[str, Any]      =		self.config.features.arrow_schema
         if all(not require_storage_cast(SCREAMING_SNAKE_CASE) for feature in self.config.features.values()):
            # cheaper cast
            _lowerCamelCase  :				Any      =		pa_table.cast(SCREAMING_SNAKE_CASE)
         else:
            # more expensive cast; allows str <-> int/float or str to Audio for example
            _lowerCamelCase  :				Any      =		table_cast(SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE)
         return pa_table
      else:
         return pa_table.cast(pa.schema({"""text""": pa.string()}))





   def 		UpperCamelCase_     (       self			,      SCREAMING_SNAKE_CASE)     ->     Any:
      _lowerCamelCase  :				Optional[Any]      =		list(self.config.features) if self.config.features is not None else ["""text"""]
      for file_idx, file in enumerate(itertools.chain.from_iterable(SCREAMING_SNAKE_CASE)):
         # open in text mode, by default translates universal newlines ("\n", "\r\n" and "\r") into "\n"
         with open(SCREAMING_SNAKE_CASE			,      encoding=self.config.encoding			,      errors=self.config.errors) as f:
            if self.config.sample_by == "line":
               _lowerCamelCase  :				Union[str, Any]      =		0
               while True:
                  _lowerCamelCase  :				int      =		f.read(self.config.chunksize)
                  if not batch:
                     break
                  batch += f.readline()  # finish current line
                  # StringIO.readlines, by default splits only on "\n" (and keeps line breaks)
                  _lowerCamelCase  :				List[str]      =		StringIO(SCREAMING_SNAKE_CASE).readlines()
                  if not self.config.keep_linebreaks:
                     _lowerCamelCase  :				Optional[Any]      =		[line.rstrip("""\n""") for line in batch]
                  _lowerCamelCase  :				Any      =		pa.Table.from_arrays([pa.array(SCREAMING_SNAKE_CASE)]			,      names=SCREAMING_SNAKE_CASE)
                  # Uncomment for debugging (will print the Arrow table size and elements)
                  # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
                  # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
                  yield (file_idx, batch_idx), self._cast_table(SCREAMING_SNAKE_CASE)
                  batch_idx += 1
            elif self.config.sample_by == "paragraph":
               _lowerCamelCase  :				Optional[Any]      =		0
               _lowerCamelCase  :				Dict      =		""""""
               while True:
                  _lowerCamelCase  :				Union[str, Any]      =		f.read(self.config.chunksize)
                  if not new_batch:
                     break
                  batch += new_batch
                  batch += f.readline()  # finish current line
                  _lowerCamelCase  :				Any      =		batch.split("""\n\n""")
                  _lowerCamelCase  :				Dict      =		pa.Table.from_arrays(
                      [pa.array([example for example in batch[:-1] if example])]			,      names=SCREAMING_SNAKE_CASE)
                  # Uncomment for debugging (will print the Arrow table size and elements)
                  # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
                  # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
                  yield (file_idx, batch_idx), self._cast_table(SCREAMING_SNAKE_CASE)
                  batch_idx += 1
                  _lowerCamelCase  :				Union[str, Any]      =		batch[-1]
               if batch:
                  _lowerCamelCase  :				Optional[int]      =		pa.Table.from_arrays([pa.array([batch])]			,      names=SCREAMING_SNAKE_CASE)
                  yield (file_idx, batch_idx), self._cast_table(SCREAMING_SNAKE_CASE)
            elif self.config.sample_by == "document":
               _lowerCamelCase  :				Tuple      =		f.read()
               _lowerCamelCase  :				List[Any]      =		pa.Table.from_arrays([pa.array([text])]			,      names=SCREAMING_SNAKE_CASE)
               yield file_idx, self._cast_table(SCREAMING_SNAKE_CASE)

