

'''simple docstring'''


import logging
import os
from logging import (
    CRITICAL,  # NOQA
    DEBUG,  # NOQA
    ERROR,  # NOQA
    FATAL,  # NOQA
    INFO,  # NOQA
    NOTSET,  # NOQA
    WARN,  # NOQA
    WARNING,  # NOQA
)
from typing import Optional

from tqdm import auto as tqdm_lib


lowerCAmelCase__						:       Optional[Any]										=						{
    """debug""": logging.DEBUG,
    """info""": logging.INFO,
    """warning""": logging.WARNING,
    """error""": logging.ERROR,
    """critical""": logging.CRITICAL,
}

lowerCAmelCase__						:       Optional[int]										=						logging.WARNING




def 	_a       (				):

  """simple docstring"""

  snake_case__						:       str       						=  os.getenv('''DATASETS_VERBOSITY'''   ,							__lowerCAmelCase     )
  if env_level_str:
    if env_level_str in log_levels:
      return log_levels[env_level_str]
    else:
      logging.getLogger().warning(
          F"""Unknown option DATASETS_VERBOSITY={env_level_str}, """
          F"""has to be one of: { ', '.join(log_levels.keys()     ) }"""     )
  return _default_log_level




def 	_a       (				):

  """simple docstring"""

  return __name__.split('''.'''     )[0]




def 	_a       (				):

  """simple docstring"""

  return logging.getLogger(_get_library_name()     )




def 	_a       (				):

  """simple docstring"""

  snake_case__						:       str       						=  _get_library_root_logger()
  library_root_logger.setLevel(_get_default_logging_level()     )




def 	_a       (				):

  """simple docstring"""

  snake_case__						:       Optional[Any]       						=  _get_library_root_logger()
  library_root_logger.setLevel(logging.NOTSET     )




def 	_a       (				__lowerCAmelCase		:      Optional[str] = None     ):

  """simple docstring"""

  if name is None:
    snake_case__						:       Any       						=  _get_library_name()
  return logging.getLogger(__lowerCAmelCase     )




def 	_a       (				):

  """simple docstring"""

  return _get_library_root_logger().getEffectiveLevel()




def 	_a       (				__lowerCAmelCase		:      int     ):

  """simple docstring"""

  _get_library_root_logger().setLevel(__lowerCAmelCase     )




def 	_a       (				):

  """simple docstring"""

  return set_verbosity(__lowerCAmelCase     )




def 	_a       (				):

  """simple docstring"""

  return set_verbosity(__lowerCAmelCase     )




def 	_a       (				):

  """simple docstring"""

  return set_verbosity(__lowerCAmelCase     )




def 	_a       (				):

  """simple docstring"""

  return set_verbosity(__lowerCAmelCase     )




def 	_a       (				):

  """simple docstring"""

  snake_case__						:       Optional[int]       						=  False




def 	_a       (				):

  """simple docstring"""

  snake_case__						:       int       						=  True


# Configure the library root logger at the module level (singleton-like)
_configure_library_root_logger()




class     a			:






      """simple docstring"""




      def __init__(							self					:      int			,			*snake_case_					:      Any			,			**snake_case_					:      Union[str, Any]  ):  # pylint: disable=unused-argument



        '''simple docstring'''



        snake_case__						:       int       						=  args[0] if args else None







      def __iter__(							self					:      List[str]  ):



        '''simple docstring'''



        return iter(self._iterator  )







      def __getattr__(							self					:      Any			,			snake_case_					:      List[str]  ):



        '''simple docstring'''



        def empty_fn(*snake_case_					:      Optional[Any]			,			**snake_case_					:      Optional[int]  ):  # pylint: disable=unused-argument
          return

        return empty_fn







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



        '''simple docstring'''



        return self







      def __exit__(							self					:      Optional[Any]			,			snake_case_					:      int			,			snake_case_					:      str			,			snake_case_					:      Optional[int]  ):



        '''simple docstring'''



        return





lowerCAmelCase__						:       Tuple										=						True




class     a			:






      """simple docstring"""




      def __call__(							self					:      List[Any]			,			*snake_case_					:      int			,			snake_case_					:      Union[str, Any]=False			,			**snake_case_					:      Union[str, Any]  ):



        '''simple docstring'''



        if _tqdm_active and not disable:
          return tqdm_lib.tqdm(*snake_case_			,			**snake_case_  )
        else:
          return EmptyTqdm(*snake_case_			,			**snake_case_  )







      def       __magic_name__							(							self					:      int			,			*snake_case_					:      Tuple			,			**snake_case_					:      List[str]  ):



        '''simple docstring'''



        snake_case__						:       Optional[Any]       						=  None
        if _tqdm_active:
          return tqdm_lib.tqdm.set_lock(*snake_case_			,			**snake_case_  )







      def       __magic_name__							(							self					:      Optional[int]  ):



        '''simple docstring'''



        if _tqdm_active:
          return tqdm_lib.tqdm.get_lock()





lowerCAmelCase__						:       Any										=						_tqdm_cls()




def 	_a       (				):

  """simple docstring"""

  global _tqdm_active
  return bool(_tqdm_active     )




def 	_a       (				):

  """simple docstring"""

  global _tqdm_active
  snake_case__						:       int       						=  True





def 	_a       (				):

  """simple docstring"""

  global _tqdm_active
  snake_case__						:       str       						=  False






'''simple docstring'''


# Copyright 2022 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
import os
import subprocess

from packaging.version import Version, parse

from accelerate.commands.config.config_args import default_config_file, load_config_from_file


lowerCAmelCase__						:       List[Any]										=						"""Run commands across TPU VMs for initial setup before running `accelerate launch`."""




def 	_a       (				__lowerCAmelCase		:      Any=None     ):

		"""simple docstring"""

		if subparsers is not None:
				snake_case__						:       Tuple       						=  subparsers.add_parser('''tpu-config'''   ,							description=_description     )
		else:
				snake_case__						:       str       						=  argparse.ArgumentParser('''Accelerate tpu-config command'''   ,							description=_description     )
		# Core arguments
		snake_case__						:       Any       						=  parser.add_argument_group(
		    '''Config Arguments'''   ,							'''Arguments that can be configured through `accelerate config`.'''     )
		config_args.add_argument(
		    '''--config_file'''   ,							type=__lowerCAmelCase   ,							default=__lowerCAmelCase   ,							help='''Path to the config file to use for accelerate.'''   ,							)
		config_args.add_argument(
		    '''--tpu_name'''   ,							default=__lowerCAmelCase   ,							help='''The name of the TPU to use. If not specified, will use the TPU specified in the config file.'''   ,							)
		config_args.add_argument(
		    '''--tpu_zone'''   ,							default=__lowerCAmelCase   ,							help='''The zone of the TPU to use. If not specified, will use the zone specified in the config file.'''   ,							)
		snake_case__						:       Optional[Any]       						=  parser.add_argument_group('''TPU Arguments'''   ,							'''Arguments for options ran inside the TPU.'''     )
		pod_args.add_argument(
		    '''--use_alpha'''   ,							action='''store_true'''   ,							help='''Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.'''   ,							)
		pod_args.add_argument(
		    '''--command_file'''   ,							default=__lowerCAmelCase   ,							help='''The path to the file containing the commands to run on the pod on startup.'''   ,							)
		pod_args.add_argument(
		    '''--command'''   ,							action='''append'''   ,							nargs='''+'''   ,							help='''A command to run on the pod. Can be passed multiple times.'''   ,							)
		pod_args.add_argument(
		    '''--install_accelerate'''   ,							action='''store_true'''   ,							help='''Whether to install accelerate on the pod. Defaults to False.'''   ,							)
		pod_args.add_argument(
		    '''--accelerate_version'''   ,							default='''latest'''   ,							help='''The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify \'dev\' to install from GitHub.'''   ,							)
		pod_args.add_argument(
		    '''--debug'''   ,							action='''store_true'''   ,							help='''If set, will print the command that would be run instead of running it.'''     )

		if subparsers is not None:
				parser.set_defaults(func=__lowerCAmelCase     )
		return parser




def 	_a       (				__lowerCAmelCase		:      Optional[Any]     ):

		"""simple docstring"""

		snake_case__						:       Optional[int]       						=  None

		# Get the default from the config file if it exists.
		if args.config_file is not None or os.path.isfile(__lowerCAmelCase     ):
				snake_case__						:       Tuple       						=  load_config_from_file(args.config_file     )
				if not args.command_file and defaults.command_file is not None and not args.command:
						snake_case__						:       Optional[int]       						=  defaults.command_file
				if not args.command and defaults.commands is not None:
						snake_case__						:       Union[str, Any]       						=  defaults.commands
				if not args.tpu_name:
						snake_case__						:       Union[str, Any]       						=  defaults.tpu_name
				if not args.tpu_zone:
						snake_case__						:       Optional[Any]       						=  defaults.tpu_zone
		if args.accelerate_version == "dev":
				snake_case__						:       Tuple       						=  '''git+https://github.com/huggingface/accelerate.git'''
		elif args.accelerate_version == "latest":
				snake_case__						:       Union[str, Any]       						=  '''accelerate -U'''
		elif isinstance(parse(args.accelerate_version     )   ,							__lowerCAmelCase     ):
				snake_case__						:       Any       						=  F"""accelerate=={args.accelerate_version}"""

		if not args.command_file and not args.command:
				raise ValueError('''You must specify either a command file or a command to run on the pod.'''     )

		if args.command_file:
				with open(args.command_file   ,							'''r'''     ) as f:
						snake_case__						:       str       						=  [f.read().splitlines()]

    # To turn list of lists into list of strings
		if isinstance(args.command[0]   ,							__lowerCAmelCase     ):
				snake_case__						:       List[Any]       						=  [line for cmd in args.command for line in cmd]
		# Default to the shared folder and install accelerate
		snake_case__						:       Optional[int]       						=  ['''cd /usr/share''']
		if args.install_accelerate:
				new_cmd += [F"""pip install {args.accelerate_version}"""]
		new_cmd += args.command
		snake_case__						:       Tuple       						=  '''; '''.join(__lowerCAmelCase     )

		# Then send it to gcloud
		# Eventually try to use google-api-core to do this instead of subprocess
		snake_case__						:       str       						=  ['''gcloud''']
		if args.use_alpha:
				cmd += ["alpha"]
		cmd += [
		    "compute",
		    "tpus",
		    "tpu-vm",
		    "ssh",
		    args.tpu_name,
		    "--zone",
		    args.tpu_zone,
		    "--command",
		    args.command,
		    "--worker",
		    "all",
		]
		if args.debug:
				print(F"""Running {' '.join(__lowerCAmelCase     )}"""     )
				return
		subprocess.run(__lowerCAmelCase     )
		print('''Successfully setup pod.'''     )





def 	_a       (				):

		"""simple docstring"""

		snake_case__						:       Dict       						=  tpu_command_parser()
		snake_case__						:       Dict       						=  parser.parse_args()

		tpu_command_launcher(__lowerCAmelCase     )



