"""simple docstring"""



import json
import os
import unittest

from transformers import CLIPTokenizer, CLIPTokenizerFast
from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES
from transformers.testing_utils import require_ftfy, require_tokenizers

from ...test_tokenization_common import TokenizerTesterMixin






@require_tokenizers
class 				snake_case__     (   snake_case_,		unittest.TestCase   ):
 _snake_case   :			str           =		CLIPTokenizer
 _snake_case   :			Optional[Any]           =		CLIPTokenizerFast
 _snake_case   :			List[Any]           =		True
 _snake_case   :			List[str]           =		{}
 _snake_case   :			Optional[Any]           =		False


 def 		a__ (				self		):
        super().setUp()

        # fmt: off
        __a     				=  ["l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"]
        # fmt: on
        __a     				=  dict(zip(lowerCamelCase  ,						range(len(lowerCamelCase		)		)		)		)
        __a     				=  ["#version: 0.2", "l o", "lo w</w>", "e r</w>"]
        __a     				=  {"unk_token": "<unk>"}

        __a     				=  os.path.join(self.tmpdirname  ,						VOCAB_FILES_NAMES["vocab_file"]		)
        __a     				=  os.path.join(self.tmpdirname  ,						VOCAB_FILES_NAMES["merges_file"]		)
        with open(self.vocab_file  ,						"w"  ,						encoding="utf-8"		) as fp:
               fp.write(json.dumps(lowerCamelCase		) + "\n"		)
        with open(self.merges_file  ,						"w"  ,						encoding="utf-8"		) as fp:
               fp.write("\n".join(lowerCamelCase		)		)


 def 		a__ (				self  ,						**lowerCamelCase		):
        kwargs.update(self.special_tokens_map		)
        return CLIPTokenizer.from_pretrained(self.tmpdirname  ,						**lowerCamelCase		)


 def 		a__ (				self  ,						**lowerCamelCase		):
        kwargs.update(self.special_tokens_map		)
        return CLIPTokenizerFast.from_pretrained(self.tmpdirname  ,						**lowerCamelCase		)


 def 		a__ (				self  ,						lowerCamelCase		):
        __a     				=  "lower newer"
        __a     				=  "lower newer"
        return input_text, output_text


 def 		a__ (				self		):
        __a     				=  CLIPTokenizer(self.vocab_file  ,						self.merges_file  ,						**self.special_tokens_map		)
        __a     				=  "lower newer"
        __a     				=  ["lo", "w", "er</w>", "n", "e", "w", "er</w>"]
        __a     				=  tokenizer.tokenize(lowerCamelCase		)
        self.assertListEqual(lowerCamelCase  ,						lowerCamelCase		)

        __a     				=  tokens + [tokenizer.unk_token]
        __a     				=  [10, 2, 16, 9, 3, 2, 16, 20]
        self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCamelCase		)  ,						lowerCamelCase		)


 @require_ftfy
 def 		a__ (				self		):
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
               with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})"		):
                      __a     				=  self.tokenizer_class.from_pretrained(lowerCamelCase  ,						**lowerCamelCase		)
                      __a     				=  self.rust_tokenizer_class.from_pretrained(lowerCamelCase  ,						**lowerCamelCase		)

                      __a     				=  "A\n'll 11p223RF☆ho!!to?'d'd''d of a cat to-$''d."
                      __a     				=  tokenizer_s.tokenize(lowerCamelCase		)
                      __a     				=  tokenizer_r.tokenize(lowerCamelCase		)

                      self.assertListEqual(lowerCamelCase  ,						lowerCamelCase		)

                      # Test that the tokenization is identical on an example containing a character (Latin Small Letter A
                      # with Tilde) encoded in 2 different ways
                      __a     				=  "xa\u0303y" + " " + "x\xe3y"
                      __a     				=  tokenizer_s.tokenize(lowerCamelCase		)
                      __a     				=  tokenizer_r.tokenize(lowerCamelCase		)

                      self.assertListEqual(lowerCamelCase  ,						lowerCamelCase		)

                      # Test that the tokenization is identical on unicode of space type
                      __a     				=  [
                          "\u0009",  # (horizontal tab, '\t')
                          "\u000B",  # (vertical tab)
                          "\u000C",  # (form feed)
                          "\u0020",  # (space, ' ')
                          "\u200E",  # (left-to-right mark):w
                          "\u200F",  # (right-to-left mark)
                      ]
                      for unicode_seq in spaces_unicodes:
                             __a     				=  tokenizer_s.tokenize(lowerCamelCase		)
                             __a     				=  tokenizer_r.tokenize(lowerCamelCase		)

                             self.assertListEqual(lowerCamelCase  ,						lowerCamelCase		)

                      # Test that the tokenization is identical on unicode of line break type
                      __a     				=  [
                          "\u000A",  # (line feed, '\n')
                          "\r\n",  # (carriage return and line feed, '\r\n')
                          "\u000D",  # (carriage return, '\r')
                          "\r",  # (carriage return, '\r')
                          "\u000D",  # (carriage return, '\r')
                          "\u2028",  # (line separator)
                          "\u2029",  # (paragraph separator)
                          # "\u0085", # (next line)
                      ]

                      # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms
                      # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a
                      # space (and thus into an empty list).

                      for unicode_seq in line_break_unicodes:
                             __a     				=  tokenizer_s.tokenize(lowerCamelCase		)
                             __a     				=  tokenizer_r.tokenize(lowerCamelCase		)

                             self.assertListEqual(lowerCamelCase  ,						lowerCamelCase		)


 def 		a__ (				self		):
        # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space`
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
               with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})"		):
                      __a     				=  "hello"  # `hello` is a token in the vocabulary of `pretrained_name`
                      __a     				=  F"{text_of_1_token} {text_of_1_token}"

                      __a     				=  self.rust_tokenizer_class.from_pretrained(
                          lowerCamelCase  ,						use_fast=lowerCamelCase  ,						)
                      __a     				=  tokenizer_r(lowerCamelCase  ,						return_offsets_mapping=lowerCamelCase  ,						add_special_tokens=lowerCamelCase		)
                      self.assertEqual(encoding.offset_mapping[0]  ,						(0, len(lowerCamelCase		))		)
                      self.assertEqual(
                          encoding.offset_mapping[1]  ,						(len(lowerCamelCase		) + 1, len(lowerCamelCase		) + 1 + len(lowerCamelCase		))  ,						)

                      __a     				=  F" {text}"

                      __a     				=  self.rust_tokenizer_class.from_pretrained(
                          lowerCamelCase  ,						use_fast=lowerCamelCase  ,						)
                      __a     				=  tokenizer_r(lowerCamelCase  ,						return_offsets_mapping=lowerCamelCase  ,						add_special_tokens=lowerCamelCase		)
                      self.assertEqual(encoding.offset_mapping[0]  ,						(1, 1 + len(lowerCamelCase		))		)
                      self.assertEqual(
                          encoding.offset_mapping[1]  ,						(1 + len(lowerCamelCase		) + 1, 1 + len(lowerCamelCase		) + 1 + len(lowerCamelCase		))  ,						)


 def 		a__ (				self		):
        # Test related to the breaking change introduced in transformers v4.17.0
        # We need to check that an error in raised when the user try to load a previous version of the tokenizer.
        with self.assertRaises(lowerCamelCase		) as context:
               self.rust_tokenizer_class.from_pretrained("robot-test/old-clip-tokenizer"		)

        self.assertTrue(
            context.exception.args[0].startswith(
                "The `backend_tokenizer` provided does not match the expected format."		)		)


 @require_ftfy
 def 		a__ (				self		):
        super().test_tokenization_python_rust_equals()






 def 		a__ (				self		):
        # CLIP always lower cases letters
        pass

"""simple docstring"""



import collections
import os
from typing import List, Optional, Tuple

from transformers.utils import is_jieba_available, requires_backends


if is_jieba_available():
   import jieba

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


SCREAMING_SNAKE_CASE__:Tuple			=	logging.get_logger(__name__)

SCREAMING_SNAKE_CASE__:List[Any]			=	{"""vocab_file""": """vocab.txt"""}

SCREAMING_SNAKE_CASE__:Optional[int]			=	{
    """vocab_file""": {
        """openbmb/cpm-ant-10b""": """https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt""",
    },
}

SCREAMING_SNAKE_CASE__:Tuple			=	{
    """openbmb/cpm-ant-10b""": 1024,
}



def 					_lowerCamelCase(					a							):
       __a     				=  collections.OrderedDict()
       with open(a ,  "r" ,  encoding="utf-8"							) as reader:
              __a     				=  reader.readlines()
       for index, token in enumerate(a							):
              __a     				=  token.rstrip("\n"							)
              __a     				=  index
       return vocab






class 				snake_case__     (   snake_case_   ):


 def __init__(				self  ,						lowerCamelCase  ,						lowerCamelCase="<unk>"  ,						lowerCamelCase=200		):
        __a     				=  vocab
        __a     				=  unk_token
        __a     				=  max_input_chars_per_word






 def 		a__ (				self  ,						lowerCamelCase		):
        __a     				=  list(lowerCamelCase		)
        if len(lowerCamelCase		) > self.max_input_chars_per_word:
               return [self.unk_token]

        __a     				=  0
        __a     				=  []
        while start < len(lowerCamelCase		):
               __a     				=  len(lowerCamelCase		)
               __a     				=  None
               while start < end:
                      __a     				=  "".join(chars[start:end]		)
                      if substr in self.vocab:
                             __a     				=  substr
                             break
                      end -= 1
               if cur_substr is None:
                      sub_tokens.append(self.unk_token		)
                      start += 1
               else:
                      sub_tokens.append(lowerCamelCase		)
                      __a     				=  end

        return sub_tokens






class 				snake_case__     (   snake_case_   ):
 _snake_case   :			Optional[int]           =		VOCAB_FILES_NAMES
 _snake_case   :			Optional[int]           =		PRETRAINED_VOCAB_FILES_MAP
 _snake_case   :			Optional[Any]           =		PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 _snake_case   :			int           =		["""input_ids""", """attention_mask"""]
 _snake_case   :			int           =		False


 def __init__(				self  ,						lowerCamelCase  ,						lowerCamelCase="<d>"  ,						lowerCamelCase="</d>"  ,						lowerCamelCase="<s>"  ,						lowerCamelCase="</s>"  ,						lowerCamelCase="<pad>"  ,						lowerCamelCase="<unk>"  ,						lowerCamelCase="</n>"  ,						lowerCamelCase="</_>"  ,						lowerCamelCase="left"  ,						**lowerCamelCase  ,						):
        requires_backends(self  ,						["jieba"]		)
        super().__init__(
            bod_token=lowerCamelCase  ,						eod_token=lowerCamelCase  ,						bos_token=lowerCamelCase  ,						eos_token=lowerCamelCase  ,						pad_token=lowerCamelCase  ,						unk_token=lowerCamelCase  ,						line_token=lowerCamelCase  ,						space_token=lowerCamelCase  ,						padding_side=lowerCamelCase  ,						**lowerCamelCase  ,						)
        __a     				=  bod_token
        __a     				=  eod_token
        __a     				=  load_vocab(lowerCamelCase		)
        __a     				=  self.encoder[space_token]
        __a     				=  self.encoder[line_token]

        del self.encoder[space_token]
        del self.encoder[line_token]

        __a     				=  collections.OrderedDict(sorted(self.encoder.items()  ,						key=lambda lowerCamelCase		: x[1]		)		)
        __a     				=  {v: k for k, v in self.encoder.items()}

        __a     				=  WordpieceTokenizer(vocab=self.encoder  ,						unk_token=self.unk_token		)


 @property
 def 		a__ (				self		):
        return self.encoder[self.bod_token]


 @property
 def 		a__ (				self		):
        return self.encoder[self.eod_token]


 @property
 def 		a__ (				self		):
        return self.encoder["\n"]


 @property
 def 		a__ (				self		):
        return len(self.encoder		)


 def 		a__ (				self		):
        return dict(self.encoder  ,						**self.added_tokens_encoder		)


 def 		a__ (				self  ,						lowerCamelCase		):
        __a     				=  []
        for x in jieba.cut(lowerCamelCase  ,						cut_all=lowerCamelCase		):
               output_tokens.extend(self.wordpiece_tokenizer.tokenize(lowerCamelCase		)		)
        return output_tokens


 def 		a__ (				self  ,						lowerCamelCase  ,						**lowerCamelCase		):
        __a     				=  [i for i in token_ids if i >= 0]
        __a     				=  [
            x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id
        ]
        return super()._decode(lowerCamelCase  ,						**lowerCamelCase		)


 def 		a__ (				self  ,						lowerCamelCase		):
        return token in self.encoder


 def 		a__ (				self  ,						lowerCamelCase		):
        return "".join(lowerCamelCase		)


 def 		a__ (				self  ,						lowerCamelCase		):
        return self.encoder.get(lowerCamelCase  ,						self.encoder.get(self.unk_token		)		)


 def 		a__ (				self  ,						lowerCamelCase		):
        return self.decoder.get(lowerCamelCase  ,						self.unk_token		)


 def 		a__ (				self  ,						lowerCamelCase  ,						lowerCamelCase = None		):
        if os.path.isdir(lowerCamelCase		):
               __a     				=  os.path.join(
                   lowerCamelCase  ,						(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]		)
        else:
               __a     				=  (filename_prefix + "-" if filename_prefix else "") + save_directory
        __a     				=  0
        if " " in self.encoder:
               __a     				=  self.encoder[" "]
               del self.encoder[" "]
        if "\n" in self.encoder:
               __a     				=  self.encoder["\n"]
               del self.encoder["\n"]
        __a     				=  collections.OrderedDict(sorted(self.encoder.items()  ,						key=lambda lowerCamelCase		: x[1]		)		)
        with open(lowerCamelCase  ,						"w"  ,						encoding="utf-8"		) as writer:
               for token, token_index in self.encoder.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!"		)
                             __a     				=  token_index
                      writer.write(token + "\n"		)
                      index += 1
        return (vocab_file,)


 def 		a__ (				self  ,						lowerCamelCase  ,						lowerCamelCase = None		):
        if token_ids_a is None:
               return [self.bos_token_id] + token_ids_a
        return [self.bos_token_id] + token_ids_a + [self.bos_token_id] + token_ids_a






 def 		a__ (				self  ,						lowerCamelCase  ,						lowerCamelCase = None  ,						lowerCamelCase = False		):

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

        if token_ids_a is not None:
               return [1] + ([0] * len(lowerCamelCase		)) + [1] + ([0] * len(lowerCamelCase		))
        return [1] + ([0] * len(lowerCamelCase		))
