

import unittest

from transformers import (
    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TextClassificationPipeline,
    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.
_a:    List[Any] 							=			{"""LayoutLMv2Config""", """LayoutLMv3Config"""}

@is_pipeline_test
class 						__UpperCamelCase    (					unittest.TestCase						):
	SCREAMING_SNAKE_CASE__    				=     MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
	SCREAMING_SNAKE_CASE__    				=     TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

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




	@require_torch
	def       __A					(		self	:						Optional[int]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			pipeline(
		    task="text-classification"		,	model="hf-internal-testing/tiny-random-distilbert"		,	framework="pt"							)

		UpperCAmelCase_       				=			text_classifier("This is great !"							)
		self.assertEqual(nested_simplify(lowerCAmelCase							)		,	[{"label": "LABEL_0", "score": 0.504}]							)

		UpperCAmelCase_       				=			text_classifier("This is great !"		,	top_k=2							)
		self.assertEqual(
		    nested_simplify(lowerCAmelCase							)		,	[{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}]							)

		UpperCAmelCase_       				=			text_classifier(["This is great !", "This is bad"]		,	top_k=2							)
		self.assertEqual(
		    nested_simplify(lowerCAmelCase							)		,	[
		        [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}],
		        [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}],
		    ]		,	)

		UpperCAmelCase_       				=			text_classifier("This is great !"		,	top_k=1							)
		self.assertEqual(nested_simplify(lowerCAmelCase							)		,	[{"label": "LABEL_0", "score": 0.504}]							)

		# Legacy behavior
		UpperCAmelCase_       				=			text_classifier("This is great !"		,	return_all_scores=lowerCAmelCase							)
		self.assertEqual(nested_simplify(lowerCAmelCase							)		,	[{"label": "LABEL_0", "score": 0.504}]							)

		UpperCAmelCase_       				=			text_classifier("This is great !"		,	return_all_scores=lowerCAmelCase							)
		self.assertEqual(
		    nested_simplify(lowerCAmelCase							)		,	[[{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}]]							)

		UpperCAmelCase_       				=			text_classifier(["This is great !", "Something else"]		,	return_all_scores=lowerCAmelCase							)
		self.assertEqual(
		    nested_simplify(lowerCAmelCase							)		,	[
		        [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}],
		        [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}],
		    ]		,	)

		UpperCAmelCase_       				=			text_classifier(["This is great !", "Something else"]		,	return_all_scores=lowerCAmelCase							)
		self.assertEqual(
		    nested_simplify(lowerCAmelCase							)		,	[
		        {"label": "LABEL_0", "score": 0.504},
		        {"label": "LABEL_0", "score": 0.504},
		    ]		,	)




	@require_torch
	def       __A					(		self	:						Union[str, Any]							):


		'''simple docstring'''







		import torch

		UpperCAmelCase_       				=			pipeline(
		    task="text-classification"		,	model="hf-internal-testing/tiny-random-distilbert"		,	framework="pt"		,	device=torch.device("cpu"							)		,	)

		UpperCAmelCase_       				=			text_classifier("This is great !"							)
		self.assertEqual(nested_simplify(lowerCAmelCase							)		,	[{"label": "LABEL_0", "score": 0.504}]							)




	@require_tf
	def       __A					(		self	:						int							):


		'''simple docstring'''







		UpperCAmelCase_       				=			pipeline(
		    task="text-classification"		,	model="hf-internal-testing/tiny-random-distilbert"		,	framework="tf"							)

		UpperCAmelCase_       				=			text_classifier("This is great !"							)
		self.assertEqual(nested_simplify(lowerCAmelCase							)		,	[{"label": "LABEL_0", "score": 0.504}]							)




	@slow
	@require_torch
	def       __A					(		self	:						List[Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			pipeline("text-classification"							)

		UpperCAmelCase_       				=			text_classifier("This is great !"							)
		self.assertEqual(nested_simplify(lowerCAmelCase							)		,	[{"label": "POSITIVE", "score": 1.0}]							)
		UpperCAmelCase_       				=			text_classifier("This is bad !"							)
		self.assertEqual(nested_simplify(lowerCAmelCase							)		,	[{"label": "NEGATIVE", "score": 1.0}]							)
		UpperCAmelCase_       				=			text_classifier("Birds are a type of animal"							)
		self.assertEqual(nested_simplify(lowerCAmelCase							)		,	[{"label": "POSITIVE", "score": 0.988}]							)




	@slow
	@require_tf
	def       __A					(		self	:						Optional[Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			pipeline("text-classification"		,	framework="tf"							)

		UpperCAmelCase_       				=			text_classifier("This is great !"							)
		self.assertEqual(nested_simplify(lowerCAmelCase							)		,	[{"label": "POSITIVE", "score": 1.0}]							)
		UpperCAmelCase_       				=			text_classifier("This is bad !"							)
		self.assertEqual(nested_simplify(lowerCAmelCase							)		,	[{"label": "NEGATIVE", "score": 1.0}]							)
		UpperCAmelCase_       				=			text_classifier("Birds are a type of animal"							)
		self.assertEqual(nested_simplify(lowerCAmelCase							)		,	[{"label": "POSITIVE", "score": 0.988}]							)




	def       __A					(		self	:						str		,	lowerCAmelCase	:						Optional[Any]		,	lowerCAmelCase	:						List[Any]		,	lowerCAmelCase	:						Dict							):


		'''simple docstring'''







		UpperCAmelCase_       				=			TextClassificationPipeline(model=lowerCAmelCase		,	tokenizer=lowerCAmelCase							)
		return text_classifier, ["HuggingFace is in", "This is another test"]




	def       __A					(		self	:						List[str]		,	lowerCAmelCase	:						Optional[Any]		,	lowerCAmelCase	:						Dict							):


		'''simple docstring'''







		UpperCAmelCase_       				=			text_classifier.model
		# Small inputs because BartTokenizer tiny has maximum position embeddings = 22
		UpperCAmelCase_       				=			"HuggingFace is in"
		UpperCAmelCase_       				=			text_classifier(lowerCAmelCase							)

		self.assertEqual(nested_simplify(lowerCAmelCase							)		,	[{"label": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							)}]							)
		self.assertTrue(outputs[0]["label"] in model.config.idalabel.values()							)

		UpperCAmelCase_       				=			["HuggingFace is in ", "Paris is in France"]
		UpperCAmelCase_       				=			text_classifier(lowerCAmelCase							)
		self.assertEqual(
		    nested_simplify(lowerCAmelCase							)		,	[{"label": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							)}, {"label": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							)}]		,	)
		self.assertTrue(outputs[0]["label"] in model.config.idalabel.values()							)
		self.assertTrue(outputs[1]["label"] in model.config.idalabel.values()							)

		# Forcing to get all results with `top_k=None`
		# This is NOT the legacy format
		UpperCAmelCase_       				=			text_classifier(lowerCAmelCase		,	top_k=lowerCAmelCase							)
		UpperCAmelCase_       				=			len(model.config.idalabel.values()							)
		self.assertEqual(
		    nested_simplify(lowerCAmelCase							)		,	[[{"label": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							)}] * N, [{"label": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							)}] * N]		,	)

		UpperCAmelCase_       				=			{"text": "HuggingFace is in ", "text_pair": "Paris is in France"}
		UpperCAmelCase_       				=			text_classifier(lowerCAmelCase							)
		self.assertEqual(
		    nested_simplify(lowerCAmelCase							)		,	{"label": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							)}		,	)
		self.assertTrue(outputs["label"] in model.config.idalabel.values()							)

		# This might be used a text pair, but tokenizer + pipe interaction
		# makes it hard to understand that it's not using the pair properly
		# https://github.com/huggingface/transformers/issues/17305
		# We disabled this usage instead as it was outputting wrong outputs.
		UpperCAmelCase_       				=			[["HuggingFace is in ", "Paris is in France"]]
		with self.assertRaises(lowerCAmelCase							):
			text_classifier(lowerCAmelCase							)

		# This used to be valid for doing text pairs
		# We're keeping it working because of backward compatibility
		UpperCAmelCase_       				=			text_classifier([[["HuggingFace is in ", "Paris is in France"]]]							)
		self.assertEqual(
		    nested_simplify(lowerCAmelCase							)		,	[{"label": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							)}]		,	)
		self.assertTrue(outputs[0]["label"] in model.config.idalabel.values()							)


import json
import os
from pathlib import Path
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple, Union

import sentencepiece

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


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

_a:    List[str] 							=			"""▁"""

_a:    Union[str, Any] 							=			{
    """vocab_file""": """vocab.json""",
    """spm_file""": """sentencepiece.bpe.model""",
}

_a:    Tuple 							=			{
    """vocab_file""": {
        """facebook/s2t-small-librispeech-asr""": (
            """https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/vocab.json"""
        ),
    },
    """spm_file""": {
        """facebook/s2t-small-librispeech-asr""": (
            """https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/sentencepiece.bpe.model"""
        )
    },
}

_a:    Optional[int] 							=			{
    """facebook/s2t-small-librispeech-asr""": 1024,
}

_a:    List[Any] 							=			["""pt""", """fr""", """ru""", """nl""", """ro""", """it""", """es""", """de"""]

_a:    Tuple 							=			{"""mustc""": MUSTC_LANGS}

class 						__UpperCamelCase    (					lowercase						):
	SCREAMING_SNAKE_CASE__    				=     VOCAB_FILES_NAMES
	SCREAMING_SNAKE_CASE__    				=     PRETRAINED_VOCAB_FILES_MAP
	SCREAMING_SNAKE_CASE__    				=     MAX_MODEL_INPUT_SIZES
	SCREAMING_SNAKE_CASE__    				=     ['input_ids', 'attention_mask']

	SCREAMING_SNAKE_CASE__    				=     []




	def __init__(		self	:						Union[str, Any]		,	lowerCAmelCase	:						str		,	lowerCAmelCase	:						Tuple		,	lowerCAmelCase	:						Tuple="<s>"		,	lowerCAmelCase	:						Optional[int]="</s>"		,	lowerCAmelCase	:						Any="<pad>"		,	lowerCAmelCase	:						Union[str, Any]="<unk>"		,	lowerCAmelCase	:						Tuple=False		,	lowerCAmelCase	:						List[Any]=False		,	lowerCAmelCase	:						Optional[int]=None		,	lowerCAmelCase	:						List[str]=None		,	lowerCAmelCase	:						Optional[Dict[str, Any]] = None		,	**lowerCAmelCase	:						Any		,	):


		'''simple docstring'''







		UpperCAmelCase_       				=			{} if sp_model_kwargs is None else sp_model_kwargs

		super().__init__(
		    bos_token=lowerCAmelCase		,	eos_token=lowerCAmelCase		,	unk_token=lowerCAmelCase		,	pad_token=lowerCAmelCase		,	do_upper_case=lowerCAmelCase		,	do_lower_case=lowerCAmelCase		,	tgt_lang=lowerCAmelCase		,	lang_codes=lowerCAmelCase		,	sp_model_kwargs=self.sp_model_kwargs		,	**lowerCAmelCase		,	)
		UpperCAmelCase_       				=			do_upper_case
		UpperCAmelCase_       				=			do_lower_case

		UpperCAmelCase_       				=			load_json(lowerCAmelCase							)
		UpperCAmelCase_       				=			{v: k for k, v in self.encoder.items()}
		UpperCAmelCase_       				=			spm_file
		UpperCAmelCase_       				=			load_spm(lowerCAmelCase		,	self.sp_model_kwargs							)

		if lang_codes is not None:
			UpperCAmelCase_       				=			lang_codes
			UpperCAmelCase_       				=			LANGUAGES[lang_codes]
			UpperCAmelCase_       				=			[F"<lang:{lang}>" for lang in self.langs]
			UpperCAmelCase_       				=			{lang: self.sp_model.PieceToId(F"<lang:{lang}>"							) for lang in self.langs}

			UpperCAmelCase_       				=			self.lang_tokens
			UpperCAmelCase_       				=			tgt_lang if tgt_lang is not None else self.langs[0]

			self.set_tgt_lang_special_tokens(self._tgt_lang							)
		else:
			UpperCAmelCase_       				=			{}




	@property
	def       __A					(		self	:						List[Any]							):


		'''simple docstring'''







		return len(self.encoder							)




	@property
	def       __A					(		self	:						Any							):


		'''simple docstring'''







		return self._tgt_lang




	@tgt_lang.setter
	def       __A					(		self	:						int		,	lowerCAmelCase	:						Optional[Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			new_tgt_lang
		self.set_tgt_lang_special_tokens(lowerCAmelCase							)




	def       __A					(		self	:						List[Any]		,	lowerCAmelCase	:						str							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.lang_code_to_id[tgt_lang]
		UpperCAmelCase_       				=			[lang_code_id]




	def       __A					(		self	:						List[str]		,	lowerCAmelCase	:						str							):


		'''simple docstring'''







		return self.sp_model.encode(lowerCAmelCase		,	out_type=lowerCAmelCase							)




	def       __A					(		self	:						str		,	lowerCAmelCase	:						int							):


		'''simple docstring'''







		return self.encoder.get(lowerCAmelCase		,	self.encoder[self.unk_token]							)




	def       __A					(		self	:						Optional[Any]		,	lowerCAmelCase	:						int							):


		'''simple docstring'''







		return self.decoder.get(lowerCAmelCase		,	self.unk_token							)




	def       __A					(		self	:						Dict		,	lowerCAmelCase	:						List[str]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			[]
		UpperCAmelCase_       				=			""
		for token in tokens:
			# make sure that special tokens are not decoded using sentencepiece model
			if token in self.all_special_tokens:
				UpperCAmelCase_       				=			self.sp_model.decode(lowerCAmelCase							)
				out_string += (decoded.upper() if self.do_upper_case else decoded) + token + " "
				UpperCAmelCase_       				=			[]
			else:
				current_sub_tokens.append(lowerCAmelCase							)
		UpperCAmelCase_       				=			self.sp_model.decode(lowerCAmelCase							)
		out_string += decoded.upper() if self.do_upper_case else decoded
		return out_string.strip()




	def       __A					(		self	:						Optional[Any]		,	lowerCAmelCase	:						List[Any]		,	lowerCAmelCase	:						Optional[int]=None							):


		'''simple docstring'''







		if token_ids_a is None:
			return self.prefix_tokens + token_ids_a + [self.eos_token_id]
		# We don't expect to process pairs, but leave the pair logic for API consistency
		return self.prefix_tokens + token_ids_a + token_ids_a + [self.eos_token_id]




	def       __A					(		self	:						Any		,	lowerCAmelCase	:						List[int]		,	lowerCAmelCase	:						Optional[List[int]] = None		,	lowerCAmelCase	:						bool = False							):


		'''simple docstring'''







		if already_has_special_tokens:
			return super().get_special_tokens_mask(
			    token_ids_a=lowerCAmelCase		,	token_ids_a=lowerCAmelCase		,	already_has_special_tokens=lowerCAmelCase							)

		UpperCAmelCase_       				=			[1] * len(self.prefix_tokens							)
		UpperCAmelCase_       				=			[1]
		if token_ids_a is None:
			return prefix_ones + ([0] * len(lowerCAmelCase							)) + suffix_ones
		return prefix_ones + ([0] * len(lowerCAmelCase							)) + ([0] * len(lowerCAmelCase							)) + suffix_ones




	def       __A					(		self	:						Optional[Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.encoder.copy()
		vocab.update(self.added_tokens_encoder							)
		return vocab




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


		'''simple docstring'''







		UpperCAmelCase_       				=			self.__dict__.copy()
		UpperCAmelCase_       				=			None
		return state




	def __setstate__(		self	:						Tuple		,	lowerCAmelCase	:						Dict							):


		'''simple docstring'''







		UpperCAmelCase_       				=			d

		# for backward compatibility
		if not hasattr(self		,	"sp_model_kwargs"							):
			UpperCAmelCase_       				=			{}

		UpperCAmelCase_       				=			load_spm(self.spm_file		,	self.sp_model_kwargs							)




	def       __A					(		self	:						Optional[Any]		,	lowerCAmelCase	:						str		,	lowerCAmelCase	:						Optional[str] = None							):


		'''simple docstring'''







		UpperCAmelCase_       				=			Path(lowerCAmelCase							)
		assert save_dir.is_dir(), F"{save_directory} should be a directory"
		UpperCAmelCase_       				=			save_dir / (
		    (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"]
		)
		UpperCAmelCase_       				=			save_dir / (
		    (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["spm_file"]
		)

		save_json(self.encoder		,	lowerCAmelCase							)

		if os.path.abspath(self.spm_file							) != os.path.abspath(lowerCAmelCase							) and os.path.isfile(self.spm_file							):
			copyfile(self.spm_file		,	lowerCAmelCase							)
		elif not os.path.isfile(self.spm_file							):
			with open(lowerCAmelCase		,	"wb"							) as fi:
				UpperCAmelCase_       				=			self.sp_model.serialized_model_proto()
				fi.write(lowerCAmelCase							)

		return (str(lowerCAmelCase							), str(lowerCAmelCase							))



def       __lowerCAmelCase      (						A       ,     A    ):
	UpperCAmelCase_       				=			sentencepiece.SentencePieceProcessor(**A    )
	spm.Load(str(A    )    )
	return spm



def       __lowerCAmelCase      (						A    ):
	with open(A       ,     "r"    ) as f:
		return json.load(A    )




def       __lowerCAmelCase      (						A       ,     A    ):
	with open(A       ,     "w"    ) as f:
		json.dump(A       ,     A       ,     indent=2    )