






"""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 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 				snake_case      (   A__=None						):
			if subparsers is not None:
						UpperCAmelCase_     : List[Any]			     =					subparsers.add_parser("env"						)
			else:
						UpperCAmelCase_     : str			     =					argparse.ArgumentParser("Accelerate env command"						)

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

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

def 				snake_case      (   A__						):
			UpperCAmelCase_     : int			     =					torch.__version__
			UpperCAmelCase_     : Union[str, Any]			     =					torch.cuda.is_available()
			UpperCAmelCase_     : Optional[int]			     =					is_xpu_available()
			UpperCAmelCase_     : Any			     =					is_npu_available()

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

			UpperCAmelCase_     : List[str]			     =					{
			    "`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(A__						),
			    "PyTorch NPU available": str(A__						),
			    "System RAM": F"""{psutil.virtual_memory().total / 10_24 ** 3:.2f} GB""",
			}
			if pt_cuda_available:
						UpperCAmelCase_     : Any			     =					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:"						)
			UpperCAmelCase_     : Tuple			     =					(
			    "\n".join([F"""\t- {prop}: {val}""" for prop, val in accelerate_config.items()]						)
			    if isinstance(A__	,A__						)
			    else F"""\t{accelerate_config}"""
			)
			print(A__						)

			UpperCAmelCase_     : Optional[int]			     =					accelerate_config

			return info

def 				snake_case      (   ):
			UpperCAmelCase_     : str			     =					env_command_parser()
			UpperCAmelCase_     : List[str]			     =					parser.parse_args()
			env_command(A__						)
			return 0


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











"""simple docstring"""
from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
			from PIL import Image

			from ..image_utils import load_image

if is_tf_available():
			import tensorflow as tf

			from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
			from ..tf_utils import stable_softmax

if is_torch_available():
			from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING

lowerCamelCase_					=      logging.get_logger(__name__)







@add_end_docstrings(__A     )
class 			UpperCamelCase_       (__A     ):





	def __init__(      self					: int	,	*lowerCAmelCase_					: Tuple	,	**lowerCAmelCase_					: List[str]						)						->			Optional[Any]:
				super().__init__(*lowerCAmelCase_	,	**lowerCAmelCase_						)
				requires_backends(self	,	"vision"						)
				self.check_model_type(
				    TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
				    if self.framework == "tf"
				    else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING						)





	def      _SCREAMING_SNAKE_CASE      (      self					: str	,	lowerCAmelCase_					: Optional[int]=None						)						->			List[Any]:
				UpperCAmelCase_     : str			     =					{}
				if top_k is not None:
							UpperCAmelCase_     : List[str]			     =					top_k
				return {}, {}, postprocess_params





	def __call__(      self					: str	,	lowerCAmelCase_					: Union[str, List[str], "Image.Image", List["Image.Image"]]	,	**lowerCAmelCase_					: Any						)						->			Tuple:
				return super().__call__(lowerCAmelCase_	,	**lowerCAmelCase_						)





	def      _SCREAMING_SNAKE_CASE      (      self					: str	,	lowerCAmelCase_					: str						)						->			Any:
				UpperCAmelCase_     : Tuple			     =					load_image(lowerCAmelCase_						)
				UpperCAmelCase_     : Dict			     =					self.image_processor(images=lowerCAmelCase_	,	return_tensors=self.framework						)
				return model_inputs





	def      _SCREAMING_SNAKE_CASE      (      self					: List[Any]	,	lowerCAmelCase_					: Dict						)						->			str:
				UpperCAmelCase_     : Any			     =					self.model(**lowerCAmelCase_						)
				return model_outputs





	def      _SCREAMING_SNAKE_CASE      (      self					: Tuple	,	lowerCAmelCase_					: Union[str, Any]	,	lowerCAmelCase_					: Optional[int]=5						)						->			Any:
				if top_k > self.model.config.num_labels:
							UpperCAmelCase_     : int			     =					self.model.config.num_labels

				if self.framework == "pt":
							UpperCAmelCase_     : str			     =					model_outputs.logits.softmax(-1						)[0]
							UpperCAmelCase_     ,	UpperCAmelCase_     : Tuple			     =					probs.topk(lowerCAmelCase_						)
				elif self.framework == "tf":
							UpperCAmelCase_     : str			     =					stable_softmax(model_outputs.logits	,	axis=-1						)[0]
							UpperCAmelCase_     : Union[str, Any]			     =					tf.math.top_k(lowerCAmelCase_	,	k=lowerCAmelCase_						)
							UpperCAmelCase_     ,	UpperCAmelCase_     : List[Any]			     =					topk.values.numpy(), topk.indices.numpy()
				else:
							raise ValueError(f"""Unsupported framework: {self.framework}"""						)

				UpperCAmelCase_     : int			     =					scores.tolist()
				UpperCAmelCase_     : Optional[Any]			     =					ids.tolist()
				return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(lowerCAmelCase_	,	lowerCAmelCase_						)]



