
# 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 platform

import numpy as np
import psutil
import torch

from accelerate import __version__ as version
from accelerate.commands.config import default_config_file, load_config_from_file

from ..utils import is_npu_available, is_xpu_available



def      __lowerCAmelCase						(							UpperCAmelCase__				:      str=None       )  ->    str:
							if subparsers is not None:
														lowerCamelCase_							  =					subparsers.add_parser("""env"""       )
							else:
														lowerCamelCase_							  =					argparse.ArgumentParser("""Accelerate env command"""       )

							parser.add_argument(
							    """--config_file"""			,				default=_UpperCAmelCase			,				help="""The config file to use for the default values in the launching script."""       )

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



def      __lowerCAmelCase						(							UpperCAmelCase__				:      List[str]       )  ->    int:
							lowerCamelCase_							  =					torch.__version__
							lowerCamelCase_							  =					torch.cuda.is_available()
							lowerCamelCase_							  =					is_xpu_available()
							lowerCamelCase_							  =					is_npu_available()

							lowerCamelCase_							  =					"""Not found"""
							# Get the default from the config file.
							if args.config_file is not None or os.path.isfile(_UpperCAmelCase       ):
														lowerCamelCase_							  =					load_config_from_file(args.config_file       ).to_dict()

							lowerCamelCase_							  =					{
							    """`Accelerate` version""": version,
							    """Platform""": platform.platform(),
							    """Python version""": platform.python_version(),
							    """Numpy version""": np.__version__,
							    """PyTorch version (GPU?)""": F'''{pt_version} ({pt_cuda_available})''',
							    """PyTorch XPU available""": str(_UpperCAmelCase       ),
							    """PyTorch NPU available""": str(_UpperCAmelCase       ),
							    """System RAM""": F'''{psutil.virtual_memory().total / 1_0_2_4 ** 3:.2f} GB''',
							}
							if pt_cuda_available:
														lowerCamelCase_							  =					torch.cuda.get_device_name()

							print("""\nCopy-and-paste the text below in your GitHub issue\n"""       )
							print("""\n""".join([F'''- {prop}: {val}''' for prop, val in info.items()]       )       )

							print("""- `Accelerate` default config:""" if args.config_file is None else """- `Accelerate` config passed:"""       )
							lowerCamelCase_							  =					(
							    """\n""".join([F'''\t- {prop}: {val}''' for prop, val in accelerate_config.items()]       )
							    if isinstance(_UpperCAmelCase			,				_UpperCAmelCase       )
							    else F'''\t{accelerate_config}'''
							)
							print(_UpperCAmelCase       )

							lowerCamelCase_							  =					accelerate_config

							return info



def      __lowerCAmelCase						(							)  ->    str:
							lowerCamelCase_							  =					env_command_parser()
							lowerCamelCase_							  =					parser.parse_args()
							env_command(_UpperCAmelCase       )
							return 0


if __name__ == "__main__":
		raise SystemExit(main())







# Copyright 2023 The HuggingFace Inc. 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 torch

from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer
from .base import PipelineTool





class       __A(				UpperCAmelCase       ):
					SCREAMING_SNAKE_CASE			    =    '''facebook/bart-large-mnli'''
					SCREAMING_SNAKE_CASE			    =    (
					    '''This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which '''
					    '''should be the text to classify, and `labels`, which should be the list of labels to use for classification. '''
					    '''It returns the most likely label in the list of provided `labels` for the input text.'''
					)
					SCREAMING_SNAKE_CASE			    =    '''text_classifier'''
					SCREAMING_SNAKE_CASE			    =    AutoTokenizer
					SCREAMING_SNAKE_CASE			    =    AutoModelForSequenceClassification

					SCREAMING_SNAKE_CASE			    =    ['''text''', ['''text''']]
					SCREAMING_SNAKE_CASE			    =    ['''text''']

					def    lowercase__      (	self					:     Union[str, Any]   ):
												super().setup()
												lowerCamelCase_							  =					self.model.config
												lowerCamelCase_							  =					-1
												for idx, label in config.idalabel.items():
																			if label.lower().startswith("""entail"""   ):
																										lowerCamelCase_							  =					int(__UpperCamelCase   )
												if self.entailment_id == -1:
																			raise ValueError("""Could not determine the entailment ID from the model config, please pass it at init."""   )

					def    lowercase__      (	self					:     Any   ,					__UpperCamelCase					:     List[Any]   ,					__UpperCamelCase					:     Optional[Any]   ):
												lowerCamelCase_							  =					labels
												return self.pre_processor(
												    [text] * len(__UpperCamelCase   )   ,					[F'''This example is {label}''' for label in labels]   ,					return_tensors="""pt"""   ,					padding="""max_length"""   ,					)



					def    lowercase__      (	self					:     List[Any]   ,					__UpperCamelCase					:     List[str]   ):
												lowerCamelCase_							  =					outputs.logits
												lowerCamelCase_							  =					torch.argmax(logits[:, 2]   ).item()
												return self._labels[label_id]





