

from typing import List, Union

import numpy as np

from ..tokenization_utils import TruncationStrategy
from ..utils import add_end_docstrings, logging
from .base import PIPELINE_INIT_ARGS, ArgumentHandler, ChunkPipeline


_lowerCamelCase    :       List[Any]        =							logging.get_logger(__name__)





class  __UpperCAmelCase					(	lowerCamelCase__						):



   def 	__magic_name__   (							self							:					str,		__A							:					Optional[int]						):
     if isinstance(__A,		__A						):
       UpperCAmelCase	:							str						=			[label.strip() for label in labels.split(''','''						) if label.strip()]
     return labels





   def __call__(							self							:					Any,		__A							:					Any,		__A							:					Tuple,		__A							:					Dict						):
     if len(__A						) == 0 or len(__A						) == 0:
       raise ValueError('''You must include at least one label and at least one sequence.'''						)
     if hypothesis_template.format(labels[0]						) == hypothesis_template:
       raise ValueError(
           (
               '''The provided hypothesis_template "{}" was not able to be formatted with the target labels. '''
               '''Make sure the passed template includes formatting syntax such as {{}} where the label should go.'''
           ).format(__A						)						)

     if isinstance(__A,		__A						):
       UpperCAmelCase	:							int						=			[sequences]

     UpperCAmelCase	:							Dict						=			[]
     for sequence in sequences:
       sequence_pairs.extend([[sequence, hypothesis_template.format(__A						)] for label in labels]						)

     return sequence_pairs, sequences






@add_end_docstrings(lowerCamelCase__						)
class  __UpperCAmelCase					(	lowerCamelCase__						):



   def __init__(							self							:					Union[str, Any],		__A							:					List[str]=ZeroShotClassificationArgumentHandler(),		*__A							:					Optional[int],		**__A							:					Optional[Any]						):
     UpperCAmelCase	:							Optional[Any]						=			args_parser
     super().__init__(*__A,		**__A						)
     if self.entailment_id == -1:
       logger.warning(
           '''Failed to determine \'entailment\' label id from the label2id mapping in the model config. Setting to '''
           '''-1. Define a descriptive label2id mapping in the model config to ensure correct outputs.'''						)



   @property
   def 	__magic_name__   (							self							:					Union[str, Any]						):
     for label, ind in self.model.config.labelaid.items():
       if label.lower().startswith('''entail'''						):
         return ind
     return -1



   def 	__magic_name__   (							self							:					str,		__A							:					int,		__A							:					List[Any]=True,		__A							:					Any=True,		__A							:					List[str]=TruncationStrategy.ONLY_FIRST,		**__A							:					List[Any]						):
     UpperCAmelCase	:							Dict						=			self.framework
     if self.tokenizer.pad_token is None:
       # Override for tokenizers not supporting padding
       logger.error(
           '''Tokenizer was not supporting padding necessary for zero-shot, attempting to use '''
           ''' `pad_token=eos_token`'''						)
       UpperCAmelCase	:							Optional[int]						=			self.tokenizer.eos_token
     try:
       UpperCAmelCase	:							int						=			self.tokenizer(
           __A,		add_special_tokens=__A,		return_tensors=__A,		padding=__A,		truncation=__A,		)
     except Exception as e:
       if "too short" in str(__A						):
         # tokenizers might yell that we want to truncate
         # to a value that is not even reached by the input.
         # In that case we don't want to truncate.
         # It seems there's not a really better way to catch that
         # exception.

         UpperCAmelCase	:							Dict						=			self.tokenizer(
             __A,		add_special_tokens=__A,		return_tensors=__A,		padding=__A,		truncation=TruncationStrategy.DO_NOT_TRUNCATE,		)
       else:
         raise e

     return inputs



   def 	__magic_name__   (							self							:					str,		**__A							:					int						):
     if kwargs.get('''multi_class''',		__A						) is not None:
       UpperCAmelCase	:							Any						=			kwargs['''multi_class''']
       logger.warning(
           '''The `multi_class` argument has been deprecated and renamed to `multi_label`. '''
           '''`multi_class` will be removed in a future version of Transformers.'''						)
     UpperCAmelCase	:							Tuple						=			{}
     if "candidate_labels" in kwargs:
       UpperCAmelCase	:							List[str]						=			self._args_parser._parse_labels(kwargs['''candidate_labels''']						)
     if "hypothesis_template" in kwargs:
       UpperCAmelCase	:							int						=			kwargs['''hypothesis_template''']

     UpperCAmelCase	:							int						=			{}
     if "multi_label" in kwargs:
       UpperCAmelCase	:							List[str]						=			kwargs['''multi_label''']
     return preprocess_params, {}, postprocess_params



   def __call__(							self							:					List[Any],		__A							:					Union[str, List[str]],		*__A							:					Tuple,		**__A							:					Union[str, Any],		):
     if len(__A						) == 0:
       pass
     elif len(__A						) == 1 and "candidate_labels" not in kwargs:
       UpperCAmelCase	:							int						=			args[0]
     else:
       raise ValueError(F'''Unable to understand extra arguments {args}'''						)

     return super().__call__(__A,		**__A						)



   def 	__magic_name__   (							self							:					List[Any],		__A							:					Tuple,		__A							:					Optional[Any]=None,		__A							:					List[str]="This example is {}."						):
     UpperCAmelCase			,						UpperCAmelCase	:							List[Any]						=			self._args_parser(__A,		__A,		__A						)

     for i, (candidate_label, sequence_pair) in enumerate(zip(__A,		__A						)						):
       UpperCAmelCase	:							Dict						=			self._parse_and_tokenize([sequence_pair]						)

       yield {
           "candidate_label": candidate_label,
           "sequence": sequences[0],
           "is_last": i == len(__A						) - 1,
           **model_input,
       }



   def 	__magic_name__   (							self							:					Dict,		__A							:					Dict						):
     UpperCAmelCase	:							str						=			inputs['''candidate_label''']
     UpperCAmelCase	:							List[Any]						=			inputs['''sequence''']
     UpperCAmelCase	:							int						=			{k: inputs[k] for k in self.tokenizer.model_input_names}
     UpperCAmelCase	:							List[Any]						=			self.model(**__A						)

     UpperCAmelCase	:							List[str]						=			{
         '''candidate_label''': candidate_label,
         '''sequence''': sequence,
         '''is_last''': inputs['''is_last'''],
         **outputs,
     }
     return model_outputs





   def 	__magic_name__   (							self							:					List[str],		__A							:					Optional[Any],		__A							:					int=False						):
     UpperCAmelCase	:							Union[str, Any]						=			[outputs['''candidate_label'''] for outputs in model_outputs]
     UpperCAmelCase	:							Union[str, Any]						=			[outputs['''sequence'''] for outputs in model_outputs]
     UpperCAmelCase	:							Any						=			np.concatenate([output['''logits'''].numpy() for output in model_outputs]						)
     UpperCAmelCase	:							List[Any]						=			logits.shape[0]
     UpperCAmelCase	:							Union[str, Any]						=			len(__A						)
     UpperCAmelCase	:							str						=			N // n
     UpperCAmelCase	:							Dict						=			logits.reshape((num_sequences, n, -1)						)

     if multi_label or len(__A						) == 1:
       # softmax over the entailment vs. contradiction dim for each label independently
       UpperCAmelCase	:							Union[str, Any]						=			self.entailment_id
       UpperCAmelCase	:							List[str]						=			-1 if entailment_id == 0 else 0
       UpperCAmelCase	:							Tuple						=			reshaped_outputs[..., [contradiction_id, entailment_id]]
       UpperCAmelCase	:							Dict						=			np.exp(__A						) / np.exp(__A						).sum(-1,		keepdims=__A						)
       UpperCAmelCase	:							Dict						=			scores[..., 1]
     else:
       # softmax the "entailment" logits over all candidate labels
       UpperCAmelCase	:							List[str]						=			reshaped_outputs[..., self.entailment_id]
       UpperCAmelCase	:							str						=			np.exp(__A						) / np.exp(__A						).sum(-1,		keepdims=__A						)

     UpperCAmelCase	:							Any						=			list(reversed(scores[0].argsort()						)						)
     return {
         "sequence": sequences[0],
         "labels": [candidate_labels[i] for i in top_inds],
         "scores": scores[0, top_inds].tolist(),
     }








# Copyright 2021 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

from accelerate.utils import ComputeEnvironment

from .cluster import get_cluster_input
from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file  # noqa: F401
from .config_utils import _ask_field, _ask_options, _convert_compute_environment  # noqa: F401
from .sagemaker import get_sagemaker_input


_lowerCamelCase    :       Optional[Any]        =							"Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine"

def       a__					(		)  ->						List[Any]:
  UpperCAmelCase	:							Dict						=			_ask_options(
      '''In which compute environment are you running?'''    ,			['''This machine''', '''AWS (Amazon SageMaker)''']    ,			_convert_compute_environment    ,			)
  if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
    UpperCAmelCase	:							List[Any]						=			get_sagemaker_input()
  else:
    UpperCAmelCase	:							Optional[Any]						=			get_cluster_input()
  return config

def       a__					(		UpperCAmelCase							:      Union[str, Any]=None      )  ->						List[Any]:
  if subparsers is not None:
    UpperCAmelCase	:							Optional[Any]						=			subparsers.add_parser('''config'''    ,			description=UpperCAmelCase      )
  else:
    UpperCAmelCase	:							List[str]						=			argparse.ArgumentParser('''Accelerate config command'''    ,			description=UpperCAmelCase      )

  parser.add_argument(
      '''--config_file'''    ,			default=UpperCAmelCase    ,			help=(
          '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache '''
          '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have '''
          '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed '''
          '''with \'huggingface\'.'''
      )    ,			)

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

def       a__					(		UpperCAmelCase							:      List[Any]      )  ->						Optional[int]:
  UpperCAmelCase	:							str						=			get_user_input()
  if args.config_file is not None:
    UpperCAmelCase	:							Any						=			args.config_file
  else:
    if not os.path.isdir(UpperCAmelCase      ):
      os.makedirs(UpperCAmelCase      )
    UpperCAmelCase	:							List[str]						=			default_yaml_config_file

  if config_file.endswith('''.json'''      ):
    config.to_json_file(UpperCAmelCase      )
  else:
    config.to_yaml_file(UpperCAmelCase      )
  print(f'''accelerate configuration saved at {config_file}'''      )

def       a__					(		)  ->						Dict:
  UpperCAmelCase	:							str						=			config_command_parser()
  UpperCAmelCase	:							str						=			parser.parse_args()
  config_command(UpperCAmelCase      )


if __name__ == "__main__":
     main()





