


'''simple docstring'''







import json
from typing import List, Optional, Tuple

from tokenizers import pre_tokenizers, processors

from ...tokenization_utils_base import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_mvp import MvpTokenizer


SCREAMING_SNAKE_CASE_      =			logging.get_logger(__name__)


SCREAMING_SNAKE_CASE_      =			{'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'}

# See all MVP models at https://huggingface.co/models?filter=mvp
SCREAMING_SNAKE_CASE_      =			{
    'vocab_file': {
        'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/vocab.json',
    },
    'added_tokens.json': {
        'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/added_tokens.json',
    },
    'merges_file': {
        'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/merges.txt',
    },
    'tokenizer_file': {
        'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/tokenizer.json',
    },
}

SCREAMING_SNAKE_CASE_      =			{
    'RUCAIBox/mvp': 10_24,
}


class  lowerCAmelCase_						(       snake_case__      ):





  """simple docstring"""



  a_       :List[Any]												=VOCAB_FILES_NAMES
  a_       :Union[str, Any]												=PRETRAINED_VOCAB_FILES_MAP
  a_       :Tuple												=PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  a_       :str												=["""input_ids""", """attention_mask"""]
  a_       :List[str]												=MvpTokenizer

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





       '''simple docstring'''

       super().__init__(
           SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__				,							tokenizer_file=SCREAMING_SNAKE_CASE__				,							errors=SCREAMING_SNAKE_CASE__				,							bos_token=SCREAMING_SNAKE_CASE__				,							eos_token=SCREAMING_SNAKE_CASE__				,							sep_token=SCREAMING_SNAKE_CASE__				,							cls_token=SCREAMING_SNAKE_CASE__				,							unk_token=SCREAMING_SNAKE_CASE__				,							pad_token=SCREAMING_SNAKE_CASE__				,							mask_token=SCREAMING_SNAKE_CASE__				,							add_prefix_space=SCREAMING_SNAKE_CASE__				,							trim_offsets=SCREAMING_SNAKE_CASE__				,							**SCREAMING_SNAKE_CASE__				,							)

       __a       =   json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()						)
       if pre_tok_state.get("""add_prefix_space"""				,							SCREAMING_SNAKE_CASE__						) != add_prefix_space:
            __a       =   getattr(SCREAMING_SNAKE_CASE__				,							pre_tok_state.pop("""type"""						)						)
            __a       =   add_prefix_space
            __a       =   pre_tok_class(**SCREAMING_SNAKE_CASE__						)

       __a       =   add_prefix_space

       # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`
       __a       =   """post_processor"""
       __a       =   getattr(self.backend_tokenizer				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__						)
       if tokenizer_component_instance:
            __a       =   json.loads(tokenizer_component_instance.__getstate__()						)

            # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
            if "sep" in state:
                 __a       =   tuple(state["""sep"""]						)
            if "cls" in state:
                 __a       =   tuple(state["""cls"""]						)

            __a       =   False

            if state.get("""add_prefix_space"""				,							SCREAMING_SNAKE_CASE__						) != add_prefix_space:
                 __a       =   add_prefix_space
                 __a       =   True

            if state.get("""trim_offsets"""				,							SCREAMING_SNAKE_CASE__						) != trim_offsets:
                 __a       =   trim_offsets
                 __a       =   True

            if changes_to_apply:
                 __a       =   getattr(SCREAMING_SNAKE_CASE__				,							state.pop("""type"""						)						)
                 __a       =   component_class(**SCREAMING_SNAKE_CASE__						)
                 setattr(self.backend_tokenizer				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__						)

  @property
  def __a						(					self     :							str						):





       '''simple docstring'''

       if self._mask_token is None:
            if self.verbose:
                 logger.error("""Using mask_token, but it is not set yet."""						)
            return None
       return str(self._mask_token						)

  @mask_token.setter
  def __a						(					self     :							Union[str, Any]				,							SCREAMING_SNAKE_CASE__     :							int						):





       '''simple docstring'''

       __a       =   AddedToken(SCREAMING_SNAKE_CASE__				,							lstrip=SCREAMING_SNAKE_CASE__				,							rstrip=SCREAMING_SNAKE_CASE__						) if isinstance(SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__						) else value
       __a       =   value

  def __a						(					self     :							Any				,							*SCREAMING_SNAKE_CASE__     :							str				,							**SCREAMING_SNAKE_CASE__     :							Any						):





       '''simple docstring'''

       __a       =   kwargs.get("""is_split_into_words"""				,							SCREAMING_SNAKE_CASE__						)

       if is_split_into_words and not self.add_prefix_space:
            raise ValueError(
                f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True '''
                """to use it with pretokenized inputs."""						)

       return super()._batch_encode_plus(*SCREAMING_SNAKE_CASE__				,							**SCREAMING_SNAKE_CASE__						)

  def __a						(					self     :							str				,							*SCREAMING_SNAKE_CASE__     :							List[Any]				,							**SCREAMING_SNAKE_CASE__     :							List[Any]						):





       '''simple docstring'''

       __a       =   kwargs.get("""is_split_into_words"""				,							SCREAMING_SNAKE_CASE__						)

       if is_split_into_words and not self.add_prefix_space:
            raise ValueError(
                f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True '''
                """to use it with pretokenized inputs."""						)

       return super()._encode_plus(*SCREAMING_SNAKE_CASE__				,							**SCREAMING_SNAKE_CASE__						)

  def __a						(					self     :							Dict				,							SCREAMING_SNAKE_CASE__     :							str				,							SCREAMING_SNAKE_CASE__     :							Optional[str] = None						):





       '''simple docstring'''

       __a       =   self._tokenizer.model.save(SCREAMING_SNAKE_CASE__				,							name=SCREAMING_SNAKE_CASE__						)
       return tuple(SCREAMING_SNAKE_CASE__						)

  def __a						(					self     :							List[str]				,							SCREAMING_SNAKE_CASE__     :							List[Any]				,							SCREAMING_SNAKE_CASE__     :							List[Any]=None						):





       '''simple docstring'''

       __a       =   [self.bos_token_id] + token_ids_a + [self.eos_token_id]
       if token_ids_a is None:
            return output

       return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]


  def __a						(					self     :							List[Any]				,							SCREAMING_SNAKE_CASE__     :							List[int]				,							SCREAMING_SNAKE_CASE__     :							Optional[List[int]] = None						):





       '''simple docstring'''

       __a       =   [self.sep_token_id]
       __a       =   [self.cls_token_id]

       if token_ids_a is None:
            return len(cls + token_ids_a + sep						) * [0]
       return len(cls + token_ids_a + sep + sep + token_ids_a + sep						) * [0]










'''simple docstring'''







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.
SCREAMING_SNAKE_CASE_      =			{'LayoutLMv2Config', 'LayoutLMv3Config'}


@is_pipeline_test
class  lowerCAmelCase_						(       unittest.TestCase      ):





  """simple docstring"""



  a_       :List[Any]												=MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
  a_       :List[Any]												=TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

  if model_mapping is not None:
    a_       :List[Any]												={config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
  if tf_model_mapping is not None:
    a_       :Tuple												={
        config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
    }

  @require_torch
  def __a						(					self     :							int						):





       '''simple docstring'''

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

       __a       =   text_classifier("""This is great !"""						)
       self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[{"""label""": """LABEL_0""", """score""": 0.5_0_4}]						)

       __a       =   text_classifier("""This is great !"""				,							top_k=2						)
       self.assertEqual(
           nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[{"""label""": """LABEL_0""", """score""": 0.5_0_4}, {"""label""": """LABEL_1""", """score""": 0.4_9_6}]						)

       __a       =   text_classifier(["""This is great !""", """This is bad"""]				,							top_k=2						)
       self.assertEqual(
           nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[
               [{"""label""": """LABEL_0""", """score""": 0.5_0_4}, {"""label""": """LABEL_1""", """score""": 0.4_9_6}],
               [{"""label""": """LABEL_0""", """score""": 0.5_0_4}, {"""label""": """LABEL_1""", """score""": 0.4_9_6}],
           ]				,							)

       __a       =   text_classifier("""This is great !"""				,							top_k=1						)
       self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[{"""label""": """LABEL_0""", """score""": 0.5_0_4}]						)

       # Legacy behavior
       __a       =   text_classifier("""This is great !"""				,							return_all_scores=SCREAMING_SNAKE_CASE__						)
       self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[{"""label""": """LABEL_0""", """score""": 0.5_0_4}]						)

       __a       =   text_classifier("""This is great !"""				,							return_all_scores=SCREAMING_SNAKE_CASE__						)
       self.assertEqual(
           nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[[{"""label""": """LABEL_0""", """score""": 0.5_0_4}, {"""label""": """LABEL_1""", """score""": 0.4_9_6}]]						)

       __a       =   text_classifier(["""This is great !""", """Something else"""]				,							return_all_scores=SCREAMING_SNAKE_CASE__						)
       self.assertEqual(
           nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[
               [{"""label""": """LABEL_0""", """score""": 0.5_0_4}, {"""label""": """LABEL_1""", """score""": 0.4_9_6}],
               [{"""label""": """LABEL_0""", """score""": 0.5_0_4}, {"""label""": """LABEL_1""", """score""": 0.4_9_6}],
           ]				,							)

       __a       =   text_classifier(["""This is great !""", """Something else"""]				,							return_all_scores=SCREAMING_SNAKE_CASE__						)
       self.assertEqual(
           nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[
               {"""label""": """LABEL_0""", """score""": 0.5_0_4},
               {"""label""": """LABEL_0""", """score""": 0.5_0_4},
           ]				,							)

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





       '''simple docstring'''

       import torch

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

       __a       =   text_classifier("""This is great !"""						)
       self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[{"""label""": """LABEL_0""", """score""": 0.5_0_4}]						)

  @require_tf
  def __a						(					self     :							List[str]						):





       '''simple docstring'''

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

       __a       =   text_classifier("""This is great !"""						)
       self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[{"""label""": """LABEL_0""", """score""": 0.5_0_4}]						)

  @slow
  @require_torch
  def __a						(					self     :							int						):





       '''simple docstring'''

       __a       =   pipeline("""text-classification"""						)

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

  @slow
  @require_tf
  def __a						(					self     :							Union[str, Any]						):





       '''simple docstring'''

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

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

  def __a						(					self     :							Tuple				,							SCREAMING_SNAKE_CASE__     :							int				,							SCREAMING_SNAKE_CASE__     :							str				,							SCREAMING_SNAKE_CASE__     :							Tuple						):





       '''simple docstring'''

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


  def __a						(					self     :							Any				,							SCREAMING_SNAKE_CASE__     :							Any				,							SCREAMING_SNAKE_CASE__     :							Tuple						):





       '''simple docstring'''

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

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

       __a       =   ["""HuggingFace is in """, """Paris is in France"""]
       __a       =   text_classifier(SCREAMING_SNAKE_CASE__						)
       self.assertEqual(
           nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[{"""label""": ANY(SCREAMING_SNAKE_CASE__						), """score""": ANY(SCREAMING_SNAKE_CASE__						)}, {"""label""": ANY(SCREAMING_SNAKE_CASE__						), """score""": ANY(SCREAMING_SNAKE_CASE__						)}]				,							)
       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
       __a       =   text_classifier(SCREAMING_SNAKE_CASE__				,							top_k=SCREAMING_SNAKE_CASE__						)
       __a       =   len(model.config.idalabel.values()						)
       self.assertEqual(
           nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[[{"""label""": ANY(SCREAMING_SNAKE_CASE__						), """score""": ANY(SCREAMING_SNAKE_CASE__						)}] * N, [{"""label""": ANY(SCREAMING_SNAKE_CASE__						), """score""": ANY(SCREAMING_SNAKE_CASE__						)}] * N]				,							)

       __a       =   {"""text""": """HuggingFace is in """, """text_pair""": """Paris is in France"""}
       __a       =   text_classifier(SCREAMING_SNAKE_CASE__						)
       self.assertEqual(
           nested_simplify(SCREAMING_SNAKE_CASE__						)				,							{"""label""": ANY(SCREAMING_SNAKE_CASE__						), """score""": ANY(SCREAMING_SNAKE_CASE__						)}				,							)
       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.
       __a       =   [["""HuggingFace is in """, """Paris is in France"""]]
       with self.assertRaises(SCREAMING_SNAKE_CASE__						):
            text_classifier(SCREAMING_SNAKE_CASE__						)

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






