import collections
import json
import os
import re
from typing import TYPE_CHECKING, List, Optional, Tuple

import numpy as np

from ...tokenization_utils_fast import PreTrainedTokenizer
from ...utils import logging


if TYPE_CHECKING:
	from transformers.pipelines.conversational import Conversation


_snake_case								=    logging.get_logger(__name__)

_snake_case								=    {'''vocab_file''': '''vocab.txt''', '''emoji_file''': '''emoji.json'''}

_snake_case								=    {
    '''vocab_file''': {
        '''abeja/gpt-neox-japanese-2.7b''': '''https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/vocab.txt''',
    },
    '''emoji_file''': {
        '''abeja/gpt-neox-japanese-2.7b''': '''https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/emoji.json''',
    },
}

_snake_case								=    {
    '''abeja/gpt-neox-japanese-2.7b''': 2048,
}




def 	_UpperCamelCase (      snake_case__,     snake_case__				)    -> Union[str, Any]:
							with open(a_,     "r",     encoding="utf-8"				) as f:
														__UpperCAmelCase    :      Optional[Any]       = json.loads(f.read()				)

							__UpperCAmelCase    :      Any       = collections.OrderedDict()
							__UpperCAmelCase    :      Tuple       = collections.OrderedDict()
							__UpperCAmelCase    :      Dict       = collections.OrderedDict()
							with open(a_,     "r",     encoding="utf-8"				) as f:
														__UpperCAmelCase    :      Any       = f.readlines()
							__UpperCAmelCase    :      Union[str, Any]       = [[t.rstrip("\n"				)] if (t == "," or "," not in t) else t.rstrip("\n"				).split(","				) for t in token]
							for idx, b in enumerate(a_				):
														__UpperCAmelCase    :      str       = b
														__UpperCAmelCase    :      List[Any]       = idx
														for wd in b:
																					__UpperCAmelCase    :      Dict       = idx

							return vocab, raw_vocab, ids_to_tokens, emoji




class        _snake_case    (    _lowercase					):
					lowerCamelCase__:		Union[str, Any]	=  VOCAB_FILES_NAMES
					lowerCamelCase__:		Tuple	=  PRETRAINED_VOCAB_FILES_MAP
					lowerCamelCase__:		str	=  PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
					lowerCamelCase__:		Optional[int]	=  ["input_ids", "attention_mask"]
					def __init__(	self:					Tuple						,	__lowerCamelCase:					Dict						,	__lowerCamelCase:					Tuple						,	__lowerCamelCase:					int="<|endoftext|>"						,	__lowerCamelCase:					str="<|endoftext|>"						,	__lowerCamelCase:					List[Any]="<|startoftext|>"						,	__lowerCamelCase:					Optional[Any]="<|endoftext|>"						,	__lowerCamelCase:					str=False						,	**__lowerCamelCase:					List[str]						,	)     ->					Any:
												super().__init__(
												    unk_token=__lowerCamelCase						,	pad_token=__lowerCamelCase						,	bos_token=__lowerCamelCase						,	eos_token=__lowerCamelCase						,	do_clean_text=__lowerCamelCase						,	**__lowerCamelCase						,	)
												if not os.path.isfile(__lowerCamelCase  ):
																			raise ValueError(
																			    f'''Can\'t find a vocabulary file at path \'{vocab_file}\'. To load the vocabulary from a Google pretrained'''
																			    " model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"  )
												if not os.path.isfile(__lowerCamelCase  ):
																			raise ValueError(
																			    f'''Can\'t find a emoji file at path \'{emoji_file}\'. To load the emoji information from a Google'''
																			    " pretrained model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"  )
												__UpperCAmelCase    :      Tuple       = do_clean_text
												__UpperCAmelCase     ,						__UpperCAmelCase     ,						__UpperCAmelCase     ,						__UpperCAmelCase    :      Optional[int]       = load_vocab_and_emoji(__lowerCamelCase						,	__lowerCamelCase  )
												__UpperCAmelCase    :      int       = SubWordJapaneseTokenizer(
												    vocab=self.vocab						,	ids_to_tokens=self.ids_to_tokens						,	emoji=self.emoji  )
					@property
					def  _lowerCamelCase			(	self:					Optional[Any]  )     ->					Optional[Any]:
												# self.vocab contains support for character fluctuation unique to Japanese, and has a large number of vocab
												return len(self.raw_vocab  )
					def  _lowerCamelCase			(	self:					Optional[Any]  )     ->					int:
												return dict(self.raw_vocab						,	**self.added_tokens_encoder  )
					def  _lowerCamelCase			(	self:					Optional[int]						,	__lowerCamelCase:					Dict  )     ->					Dict:
												return self.subword_tokenizer.tokenize(__lowerCamelCase						,	clean=self.do_clean_text  )
					def  _lowerCamelCase			(	self:					Dict						,	__lowerCamelCase:					List[Any]  )     ->					Dict:
												return self.vocab.get(__lowerCamelCase						,	self.vocab.get(self.unk_token  )  )
					def  _lowerCamelCase			(	self:					List[Any]						,	__lowerCamelCase:					Optional[Any]  )     ->					Tuple:
												return self.subword_tokenizer.convert_id_to_token(__lowerCamelCase  )
					def  _lowerCamelCase			(	self:					Any						,	__lowerCamelCase:					Optional[int]  )     ->					Union[str, Any]:
												__UpperCAmelCase    :      int       = "".join(__lowerCamelCase  ).strip()
												return out_string
					def  _lowerCamelCase			(	self:					Any						,	__lowerCamelCase:					Dict  )     ->					List[int]:
												__UpperCAmelCase    :      Dict       = []
												for is_user, text in conversation.iter_texts():
																			input_ids.extend(self.encode(__lowerCamelCase						,	add_special_tokens=__lowerCamelCase  ) + [self.eos_token_id]  )

												if len(__lowerCamelCase  ) > self.model_max_length:
																			__UpperCAmelCase    :      Dict       = input_ids[-self.model_max_length :]
												return input_ids





					def  _lowerCamelCase			(	self:					List[Any]						,	__lowerCamelCase:					Any						,	__lowerCamelCase:					str = None  )     ->					Tuple[str]:
												__UpperCAmelCase    :      List[Any]       = 0
												if os.path.isdir(__lowerCamelCase  ):
																			__UpperCAmelCase    :      int       = os.path.join(
																			    __lowerCamelCase						,	(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]  )
																			__UpperCAmelCase    :      Tuple       = os.path.join(
																			    __lowerCamelCase						,	(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["emoji_file"]  )
												else:
																			__UpperCAmelCase    :      int       = (
																			    (filename_prefix + "-" if filename_prefix else "") + save_directory + VOCAB_FILES_NAMES["vocab_file"]
																			)
																			__UpperCAmelCase    :      Optional[Any]       = (
																			    (filename_prefix + "-" if filename_prefix else "") + save_directory + VOCAB_FILES_NAMES["emoji_file"]
																			)
												with open(__lowerCamelCase						,	"w"						,	encoding="utf-8"  ) as writer:
																			for token_index, token in self.ids_to_tokens.items():
																										if index != token_index:
																																	logger.warning(
																																	    f'''Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.'''
																																	    " Please check that the vocabulary is not corrupted!"  )
																																	__UpperCAmelCase    :      int       = token_index
																										writer.write(",".join(__lowerCamelCase  ) + "\n"  )
																										index += 1
												with open(__lowerCamelCase						,	"w"						,	encoding="utf-8"  ) as writer:
																			json.dump(self.emoji						,	__lowerCamelCase  )
												return vocab_file, emoji_file




class        _snake_case    (    _lowercase					):
					def __init__(	self:					Dict						,	__lowerCamelCase:					Tuple						,	__lowerCamelCase:					int						,	__lowerCamelCase:					Tuple  )     ->					Union[str, Any]:
												__UpperCAmelCase    :      int       = vocab  # same as swe
												__UpperCAmelCase    :      Optional[Any]       = ids_to_tokens  # same as bpe
												__UpperCAmelCase    :      int       = emoji
												__UpperCAmelCase    :      Any       = np.max([len(__lowerCamelCase  ) for w in self.vocab.keys()]  )
												__UpperCAmelCase    :      List[Any]       = re.compile(R"(https?|ftp)(:\/\/[-_\.!~*\'()a-zA-Z0-9;\/?:\@&=\+$,%#]+)"  )
												__UpperCAmelCase    :      Any       = re.compile(R"[A-Za-z0-9\._+]*@[\-_0-9A-Za-z]+(\.[A-Za-z]+)*"  )
												__UpperCAmelCase    :      List[Any]       = re.compile(R"[\(]{0,1}[0-9]{2,4}[\)\-\(]{0,1}[0-9]{2,4}[\)\-]{0,1}[0-9]{3,4}"  )
												__UpperCAmelCase    :      Optional[int]       = re.compile(
												    R"([12]\d{3}[/\-年])*(0?[1-9]|1[0-2])[/\-月]((0?[1-9]|[12][0-9]|3[01])日?)*(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*"  )
												__UpperCAmelCase    :      List[Any]       = re.compile(
												    R"(明治|大正|昭和|平成|令和|㍾|㍽|㍼|㍻|\u32ff)\d{1,2}年(0?[1-9]|1[0-2])月(0?[1-9]|[12][0-9]|3[01])日(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*"  )
												__UpperCAmelCase    :      Tuple       = re.compile(
												    R"((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*億)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*万)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*千)*(0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*(千円|万円|千万円|円|千ドル|万ドル|千万ドル|ドル|千ユーロ|万ユーロ|千万ユーロ|ユーロ)+(\(税込\)|\(税抜\)|\+tax)*"  )
												__UpperCAmelCase    :      List[str]       = "─━│┃┄┅┆┇┈┉┊┋┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿"
												__UpperCAmelCase    :      Dict       = "▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟"
												__UpperCAmelCase    :      Optional[Any]       = str.maketrans({k: "<BLOCK>" for k in keisen + blocks}  )
					def __len__(	self:					List[str]  )     ->					Union[str, Any]:
												return len(self.ids_to_tokens  )
					def  _lowerCamelCase			(	self:					List[str]						,	__lowerCamelCase:					Optional[Any]  )     ->					Optional[int]:
												__UpperCAmelCase    :      int       = self.content_repattera.sub("<URL>"						,	__lowerCamelCase  )
												__UpperCAmelCase    :      str       = self.content_repattera.sub("<EMAIL>"						,	__lowerCamelCase  )
												__UpperCAmelCase    :      str       = self.content_repattera.sub("<TEL>"						,	__lowerCamelCase  )
												__UpperCAmelCase    :      int       = self.content_repattera.sub("<DATE>"						,	__lowerCamelCase  )
												__UpperCAmelCase    :      Union[str, Any]       = self.content_repattera.sub("<DATE>"						,	__lowerCamelCase  )
												__UpperCAmelCase    :      List[Any]       = self.content_repattera.sub("<PRICE>"						,	__lowerCamelCase  )
												__UpperCAmelCase    :      Union[str, Any]       = content.translate(self.content_transa  )
												while "<BLOCK><BLOCK>" in content:
																			__UpperCAmelCase    :      str       = content.replace("<BLOCK><BLOCK>"						,	"<BLOCK>"  )
												return content
					def  _lowerCamelCase			(	self:					Dict						,	__lowerCamelCase:					Optional[int]						,	__lowerCamelCase:					List[str]=False  )     ->					Any:
												__UpperCAmelCase    :      Union[str, Any]       = text.replace(" "						,	"<SP>"  )
												__UpperCAmelCase    :      Optional[int]       = text.replace("　"						,	"<SP>"  )
												__UpperCAmelCase    :      str       = text.replace("\r\n"						,	"<BR>"  )
												__UpperCAmelCase    :      Optional[int]       = text.replace("\n"						,	"<BR>"  )
												__UpperCAmelCase    :      Optional[int]       = text.replace("\r"						,	"<BR>"  )
												__UpperCAmelCase    :      Any       = text.replace("\t"						,	"<TAB>"  )
												__UpperCAmelCase    :      Optional[Any]       = text.replace("—"						,	"ー"  )
												__UpperCAmelCase    :      Optional[Any]       = text.replace("−"						,	"ー"  )
												for k, v in self.emoji["emoji"].items():
																			if k in text:
																										__UpperCAmelCase    :      Optional[int]       = text.replace(__lowerCamelCase						,	__lowerCamelCase  )
												if clean:
																			__UpperCAmelCase    :      Tuple       = self.clean_text(__lowerCamelCase  )

												def check_simbol(__lowerCamelCase:					Optional[int]  ):
																			__UpperCAmelCase    :      List[str]       = x.encode()
																			if len(__lowerCamelCase  ) == 1 and len(__lowerCamelCase  ) == 2:
																										__UpperCAmelCase    :      List[Any]       = (int(e[0]  ) << 8) + int(e[1]  )
																										if (
																										    (c >= 0xC_2_A_1 and c <= 0xC_2_B_F)
																										    or (c >= 0xC_7_8_0 and c <= 0xC_7_8_3)
																										    or (c >= 0xC_A_B_9 and c <= 0xC_B_B_F)
																										    or (c >= 0xC_C_8_0 and c <= 0xC_D_A_2)
																										):
																																	return True
																			return False

												def checkuae(__lowerCamelCase:					Optional[int]  ):
																			__UpperCAmelCase    :      Union[str, Any]       = x.encode()
																			if len(__lowerCamelCase  ) == 1 and len(__lowerCamelCase  ) == 3:
																										__UpperCAmelCase    :      Optional[int]       = (int(e[0]  ) << 16) + (int(e[1]  ) << 8) + int(e[2]  )
																										if c >= 0xE_2_8_0_8_0 and c <= 0xE_2_B_0_7_F:
																																	return True
																			return False

												__UpperCAmelCase    :      List[str]       = 0
												__UpperCAmelCase    :      int       = []
												while pos < len(__lowerCamelCase  ):
																			__UpperCAmelCase    :      List[str]       = min(len(__lowerCamelCase  )						,	pos + self.maxlen + 1  ) if text[pos] == "<" else pos + 3
																			__UpperCAmelCase    :      Any       = []  # (token_id, token, pos)
																			for e in range(__lowerCamelCase						,	__lowerCamelCase						,	-1  ):
																										__UpperCAmelCase    :      Dict       = text[pos:e]
																										if wd in self.vocab:
																																	if wd[0] == "<" and len(__lowerCamelCase  ) > 2:
																																								__UpperCAmelCase    :      str       = [(self.vocab[wd], wd, e)]
																																								break
																																	else:
																																								candidates.append((self.vocab[wd], wd, e)  )
																			if len(__lowerCamelCase  ) > 0:
																										# the smallest token_id is adopted
																										__UpperCAmelCase     ,						__UpperCAmelCase     ,						__UpperCAmelCase    :      int       = sorted(__lowerCamelCase						,	key=lambda __lowerCamelCase  : x[0]  )[0]
																										result.append(__lowerCamelCase  )
																										__UpperCAmelCase    :      Tuple       = e
																			else:
																										__UpperCAmelCase    :      Tuple       = pos + 1
																										__UpperCAmelCase    :      Union[str, Any]       = text[pos:end]
																										if check_simbol(__lowerCamelCase  ):
																																	result.append("<KIGOU>"  )
																										elif checkuae(__lowerCamelCase  ):
																																	result.append("<U2000U2BFF>"  )
																										else:
																																	for i in wd.encode("utf-8"  ):
																																								result.append("<|byte%d|>" % i  )
																										__UpperCAmelCase    :      List[Any]       = end
												return result





					def  _lowerCamelCase			(	self:					Optional[int]						,	__lowerCamelCase:					str						,	__lowerCamelCase:					Union[str, Any]="\n"  )     ->					Tuple:
												__UpperCAmelCase    :      Union[str, Any]       = []
												__UpperCAmelCase    :      int       = []
												__UpperCAmelCase    :      Dict       = self.ids_to_tokens[index][0]
												if word[:6] == "<|byte" and word[-2:] == "|>":
																			byte_tokens.append(int(word[6:-2]  )  )
												else:
																			if len(__lowerCamelCase  ) > 0:
																										words.append(bytearray(__lowerCamelCase  ).decode("utf-8"						,	errors="replace"  )  )
																										__UpperCAmelCase    :      List[str]       = []
																			if word[:7] == "<|emoji" and word[-2:] == "|>":
																										words.append(self.emoji["emoji_inv"][word]  )
																			elif word == "<SP>":
																										words.append(" "  )
																			elif word == "<BR>":
																										words.append(__lowerCamelCase  )
																			elif word == "<TAB>":
																										words.append("\t"  )
																			elif word == "<BLOCK>":
																										words.append("▀"  )
																			elif word == "<KIGOU>":
																										words.append("ǀ"  )
																			elif word == "<U2000U2BFF>":
																										words.append("‖"  )
																			else:
																										words.append(__lowerCamelCase  )
												if len(__lowerCamelCase  ) > 0:
																			words.append(bytearray(__lowerCamelCase  ).decode("utf-8"						,	errors="replace"  )  )
												__UpperCAmelCase    :      Dict       = "".join(__lowerCamelCase  )
												return text










'''simple docstring'''


import unittest

from transformers import (
    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    Pipeline,
    ZeroShotClassificationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow

from .test_pipelines_common import ANY


# These 2 model types require different inputs than those of the usual text models.
UpperCAmelCase_					=   {"LayoutLMv2Config", "LayoutLMv3Config"}





@is_pipeline_test
class  __lowercase    (	unittest.TestCase			):
   _a    						=   MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
   _a    						=   TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

   if model_mapping is not None:
      _a    						=   {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
   if tf_model_mapping is not None:
      _a    						=   {
          config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
      }







   def 		UpperCamelCase__      (						self   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   )					->     Optional[Any]:
     __a								=       ZeroShotClassificationPipeline(
         model=UpperCamelCase   ,				tokenizer=UpperCamelCase   ,				candidate_labels=['polics', 'health']   )
     return classifier, ["Who are you voting for in 2020?", "My stomach hurts."]







   def 		UpperCamelCase__      (						self   ,				UpperCamelCase   ,				UpperCamelCase   )					->     Tuple:
     __a								=       classifier('Who are you voting for in 2020?'   ,				candidate_labels='politics'   )
     self.assertEqual(UpperCamelCase   ,				{'sequence': ANY(UpperCamelCase   ), 'labels': [ANY(UpperCamelCase   )], 'scores': [ANY(UpperCamelCase   )]}   )

     # No kwarg
     __a								=       classifier('Who are you voting for in 2020?'   ,				['politics']   )
     self.assertEqual(UpperCamelCase   ,				{'sequence': ANY(UpperCamelCase   ), 'labels': [ANY(UpperCamelCase   )], 'scores': [ANY(UpperCamelCase   )]}   )

     __a								=       classifier('Who are you voting for in 2020?'   ,				candidate_labels=['politics']   )
     self.assertEqual(UpperCamelCase   ,				{'sequence': ANY(UpperCamelCase   ), 'labels': [ANY(UpperCamelCase   )], 'scores': [ANY(UpperCamelCase   )]}   )

     __a								=       classifier('Who are you voting for in 2020?'   ,				candidate_labels='politics, public health'   )
     self.assertEqual(
         UpperCamelCase   ,				{'sequence': ANY(UpperCamelCase   ), 'labels': [ANY(UpperCamelCase   ), ANY(UpperCamelCase   )], 'scores': [ANY(UpperCamelCase   ), ANY(UpperCamelCase   )]}   )
     self.assertAlmostEqual(sum(nested_simplify(outputs['scores']   )   )   ,				1.0   )

     __a								=       classifier('Who are you voting for in 2020?'   ,				candidate_labels=['politics', 'public health']   )
     self.assertEqual(
         UpperCamelCase   ,				{'sequence': ANY(UpperCamelCase   ), 'labels': [ANY(UpperCamelCase   ), ANY(UpperCamelCase   )], 'scores': [ANY(UpperCamelCase   ), ANY(UpperCamelCase   )]}   )
     self.assertAlmostEqual(sum(nested_simplify(outputs['scores']   )   )   ,				1.0   )

     __a								=       classifier(
         'Who are you voting for in 2020?'   ,				candidate_labels='politics'   ,				hypothesis_template='This text is about {}'   )
     self.assertEqual(UpperCamelCase   ,				{'sequence': ANY(UpperCamelCase   ), 'labels': [ANY(UpperCamelCase   )], 'scores': [ANY(UpperCamelCase   )]}   )

     # https://github.com/huggingface/transformers/issues/13846
     __a								=       classifier(['I am happy']   ,				['positive', 'negative']   )
     self.assertEqual(
         UpperCamelCase   ,				[
             {'sequence': ANY(UpperCamelCase   ), 'labels': [ANY(UpperCamelCase   ), ANY(UpperCamelCase   )], 'scores': [ANY(UpperCamelCase   ), ANY(UpperCamelCase   )]}
             for i in range(1   )
         ]   ,				)
     __a								=       classifier(['I am happy', 'I am sad']   ,				['positive', 'negative']   )
     self.assertEqual(
         UpperCamelCase   ,				[
             {'sequence': ANY(UpperCamelCase   ), 'labels': [ANY(UpperCamelCase   ), ANY(UpperCamelCase   )], 'scores': [ANY(UpperCamelCase   ), ANY(UpperCamelCase   )]}
             for i in range(2   )
         ]   ,				)

     with self.assertRaises(UpperCamelCase   ):
       classifier(''   ,				candidate_labels='politics'   )

     with self.assertRaises(UpperCamelCase   ):
       classifier(UpperCamelCase   ,				candidate_labels='politics'   )

     with self.assertRaises(UpperCamelCase   ):
       classifier('Who are you voting for in 2020?'   ,				candidate_labels=''   )

     with self.assertRaises(UpperCamelCase   ):
       classifier('Who are you voting for in 2020?'   ,				candidate_labels=UpperCamelCase   )

     with self.assertRaises(UpperCamelCase   ):
       classifier(
           'Who are you voting for in 2020?'   ,				candidate_labels='politics'   ,				hypothesis_template='Not formatting template'   ,				)

     with self.assertRaises(UpperCamelCase   ):
       classifier(
           'Who are you voting for in 2020?'   ,				candidate_labels='politics'   ,				hypothesis_template=UpperCamelCase   ,				)

     self.run_entailment_id(UpperCamelCase   )







   def 		UpperCamelCase__      (						self   ,				UpperCamelCase   )					->     Optional[int]:
     __a								=       zero_shot_classifier.model.config
     __a								=       config.labelaid
     __a								=       zero_shot_classifier.entailment_id

     __a								=       {'LABEL_0': 0, 'LABEL_1': 1, 'LABEL_2': 2}
     self.assertEqual(zero_shot_classifier.entailment_id   ,				-1   )

     __a								=       {'entailment': 0, 'neutral': 1, 'contradiction': 2}
     self.assertEqual(zero_shot_classifier.entailment_id   ,				0   )

     __a								=       {'ENTAIL': 0, 'NON-ENTAIL': 1}
     self.assertEqual(zero_shot_classifier.entailment_id   ,				0   )

     __a								=       {'ENTAIL': 2, 'NEUTRAL': 1, 'CONTR': 0}
     self.assertEqual(zero_shot_classifier.entailment_id   ,				2   )

     __a								=       original_labelaid
     self.assertEqual(UpperCamelCase   ,				zero_shot_classifier.entailment_id   )







   @require_torch
   def 		UpperCamelCase__      (						self   )					->     Tuple:
     __a								=       pipeline(
         'zero-shot-classification'   ,				model='sshleifer/tiny-distilbert-base-cased-distilled-squad'   ,				framework='pt'   ,				)
     # There was a regression in 4.10 for this
     # Adding a test so we don't make the mistake again.
     # https://github.com/huggingface/transformers/issues/13381#issuecomment-912343499
     zero_shot_classifier(
         'Who are you voting for in 2020?' * 100   ,				candidate_labels=['politics', 'public health', 'science']   )







   @require_torch
   def 		UpperCamelCase__      (						self   )					->     List[str]:
     __a								=       pipeline(
         'zero-shot-classification'   ,				model='sshleifer/tiny-distilbert-base-cased-distilled-squad'   ,				framework='pt'   ,				)
     __a								=       zero_shot_classifier(
         'Who are you voting for in 2020?'   ,				candidate_labels=['politics', 'public health', 'science']   )

     self.assertEqual(
         nested_simplify(UpperCamelCase   )   ,				{
             'sequence': 'Who are you voting for in 2020?',
             'labels': ['science', 'public health', 'politics'],
             'scores': [0.333, 0.333, 0.333],
         }   ,				)







   @require_tf
   def 		UpperCamelCase__      (						self   )					->     Dict:
     __a								=       pipeline(
         'zero-shot-classification'   ,				model='sshleifer/tiny-distilbert-base-cased-distilled-squad'   ,				framework='tf'   ,				)
     __a								=       zero_shot_classifier(
         'Who are you voting for in 2020?'   ,				candidate_labels=['politics', 'public health', 'science']   )

     self.assertEqual(
         nested_simplify(UpperCamelCase   )   ,				{
             'sequence': 'Who are you voting for in 2020?',
             'labels': ['science', 'public health', 'politics'],
             'scores': [0.333, 0.333, 0.333],
         }   ,				)







   @slow
   @require_torch
   def 		UpperCamelCase__      (						self   )					->     List[str]:
     __a								=       pipeline('zero-shot-classification'   ,				model='roberta-large-mnli'   ,				framework='pt'   )
     __a								=       zero_shot_classifier(
         'Who are you voting for in 2020?'   ,				candidate_labels=['politics', 'public health', 'science']   )

     self.assertEqual(
         nested_simplify(UpperCamelCase   )   ,				{
             'sequence': 'Who are you voting for in 2020?',
             'labels': ['politics', 'public health', 'science'],
             'scores': [0.976, 0.015, 0.009],
         }   ,				)
     __a								=       zero_shot_classifier(
         'The dominant sequence transduction models are based on complex recurrent or convolutional neural networks'
         ' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder'
         ' through an attention mechanism. We propose a new simple network architecture, the Transformer, based'
         ' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two'
         ' machine translation tasks show these models to be superior in quality while being more parallelizable'
         ' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014'
         ' English-to-German translation task, improving over the existing best results, including ensembles by'
         ' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new'
         ' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small'
         ' fraction of the training costs of the best models from the literature. We show that the Transformer'
         ' generalizes well to other tasks by applying it successfully to English constituency parsing both with'
         ' large and limited training data.'   ,				candidate_labels=['machine learning', 'statistics', 'translation', 'vision']   ,				multi_label=UpperCamelCase   ,				)
     self.assertEqual(
         nested_simplify(UpperCamelCase   )   ,				{
             'sequence': (
                 'The dominant sequence transduction models are based on complex recurrent or convolutional neural'
                 ' networks in an encoder-decoder configuration. The best performing models also connect the'
                 ' encoder and decoder through an attention mechanism. We propose a new simple network'
                 ' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence'
                 ' and convolutions entirely. Experiments on two machine translation tasks show these models to be'
                 ' superior in quality while being more parallelizable and requiring significantly less time to'
                 ' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,'
                 ' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014'
                 ' English-to-French translation task, our model establishes a new single-model state-of-the-art'
                 ' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training'
                 ' costs of the best models from the literature. We show that the Transformer generalizes well to'
                 ' other tasks by applying it successfully to English constituency parsing both with large and'
                 ' limited training data.'
             ),
             'labels': ['translation', 'machine learning', 'vision', 'statistics'],
             'scores': [0.817, 0.713, 0.018, 0.018],
         }   ,				)







   @slow
   @require_tf
   def 		UpperCamelCase__      (						self   )					->     Union[str, Any]:
     __a								=       pipeline('zero-shot-classification'   ,				model='roberta-large-mnli'   ,				framework='tf'   )
     __a								=       zero_shot_classifier(
         'Who are you voting for in 2020?'   ,				candidate_labels=['politics', 'public health', 'science']   )

     self.assertEqual(
         nested_simplify(UpperCamelCase   )   ,				{
             'sequence': 'Who are you voting for in 2020?',
             'labels': ['politics', 'public health', 'science'],
             'scores': [0.976, 0.015, 0.009],
         }   ,				)
     __a								=       zero_shot_classifier(
         'The dominant sequence transduction models are based on complex recurrent or convolutional neural networks'
         ' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder'
         ' through an attention mechanism. We propose a new simple network architecture, the Transformer, based'
         ' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two'
         ' machine translation tasks show these models to be superior in quality while being more parallelizable'
         ' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014'
         ' English-to-German translation task, improving over the existing best results, including ensembles by'
         ' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new'
         ' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small'
         ' fraction of the training costs of the best models from the literature. We show that the Transformer'
         ' generalizes well to other tasks by applying it successfully to English constituency parsing both with'
         ' large and limited training data.'   ,				candidate_labels=['machine learning', 'statistics', 'translation', 'vision']   ,				multi_label=UpperCamelCase   ,				)
     self.assertEqual(
         nested_simplify(UpperCamelCase   )   ,				{
             'sequence': (
                 'The dominant sequence transduction models are based on complex recurrent or convolutional neural'
                 ' networks in an encoder-decoder configuration. The best performing models also connect the'
                 ' encoder and decoder through an attention mechanism. We propose a new simple network'
                 ' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence'
                 ' and convolutions entirely. Experiments on two machine translation tasks show these models to be'
                 ' superior in quality while being more parallelizable and requiring significantly less time to'
                 ' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,'
                 ' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014'
                 ' English-to-French translation task, our model establishes a new single-model state-of-the-art'
                 ' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training'
                 ' costs of the best models from the literature. We show that the Transformer generalizes well to'
                 ' other tasks by applying it successfully to English constituency parsing both with large and'
                 ' limited training data.'
             ),
             'labels': ['translation', 'machine learning', 'vision', 'statistics'],
             'scores': [0.817, 0.713, 0.018, 0.018],
         }   ,				)



