


'''simple docstring'''






import warnings

from transformers import AutoTokenizer
from transformers.utils import is_torch_available
from transformers.utils.generic import ExplicitEnum

from ...processing_utils import ProcessorMixin


if is_torch_available():
		import torch




class 		a__    (							__SCREAMING_SNAKE_CASE  ):





							'''simple docstring'''






							lowercase__      :       Dict     						=				"char"
							lowercase__      :       List[Any]     						=				"bpe"
							lowercase__      :       str     						=				"wp"

__UpperCAmelCase       =							(DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE)




class 		a__    (							__SCREAMING_SNAKE_CASE  ):





							'''simple docstring'''






							lowercase__      :       List[str]     						=				["image_processor", "char_tokenizer"]
							lowercase__      :       Optional[Any]     						=				"ViTImageProcessor"
							lowercase__      :       str     						=				"MgpstrTokenizer"







							def __init__(		self ,   lowerCamelCase_=None ,   lowerCamelCase_=None ,   **lowerCamelCase_       )	->							int:
														lowerCAmelCase__	       =     None
														if "feature_extractor" in kwargs:
																					warnings.warn(
																					    '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
																					    ''' instead.''' ,   _snake_case ,   )
																					lowerCAmelCase__	       =     kwargs.pop('''feature_extractor'''       )

														lowerCAmelCase__	       =     image_processor if image_processor is not None else feature_extractor
														if image_processor is None:
																					raise ValueError('''You need to specify an `image_processor`.'''       )
														if tokenizer is None:
																					raise ValueError('''You need to specify a `tokenizer`.'''       )

														lowerCAmelCase__	       =     tokenizer
														lowerCAmelCase__	       =     AutoTokenizer.from_pretrained('''gpt2'''       )
														lowerCAmelCase__	       =     AutoTokenizer.from_pretrained('''bert-base-uncased'''       )

														super().__init__(_snake_case ,   _snake_case       )







							def __call__(		self ,   lowerCamelCase_=None ,   lowerCamelCase_=None ,   lowerCamelCase_=None ,   **lowerCamelCase_       )	->							Tuple:
														if images is None and text is None:
																					raise ValueError('''You need to specify either an `images` or `text` input to process.'''       )

														if images is not None:
																					lowerCAmelCase__	       =     self.image_processor(_snake_case ,   return_tensors=_snake_case ,   **_snake_case       )
														if text is not None:
																					lowerCAmelCase__	       =     self.char_tokenizer(_snake_case ,   return_tensors=_snake_case ,   **_snake_case       )

														if text is None:
																					return inputs
														elif images is None:
																					return encodings
														else:
																					lowerCAmelCase__	       =     encodings["input_ids"]
																					return inputs







							def   __SCREAMING_SNAKE_CASE							(		self ,   lowerCamelCase_       )	->							int:
														lowerCAmelCase__	       =     sequences
														lowerCAmelCase__	       =     char_preds.size(0       )

														lowerCAmelCase__	       =     self._decode_helper(_snake_case ,   '''char'''       )
														lowerCAmelCase__	       =     self._decode_helper(_snake_case ,   '''bpe'''       )
														lowerCAmelCase__	       =     self._decode_helper(_snake_case ,   '''wp'''       )

														lowerCAmelCase__	       =     []
														lowerCAmelCase__	       =     []
														for i in range(_snake_case       ):
																					lowerCAmelCase__	       =     [char_scores[i], bpe_scores[i], wp_scores[i]]
																					lowerCAmelCase__	       =     [char_strs[i], bpe_strs[i], wp_strs[i]]
																					lowerCAmelCase__	       =     scores.index(max(_snake_case       )       )
																					final_strs.append(strs[max_score_index]       )
																					final_scores.append(scores[max_score_index]       )

														lowerCAmelCase__	       =     {}
														lowerCAmelCase__	       =     final_strs
														lowerCAmelCase__	       =     final_scores
														lowerCAmelCase__	       =     char_strs
														lowerCAmelCase__	       =     bpe_strs
														lowerCAmelCase__	       =     wp_strs
														return out







							def   __SCREAMING_SNAKE_CASE							(		self ,   lowerCamelCase_ ,   lowerCamelCase_       )	->							Dict:
														if format == DecodeType.CHARACTER:
																					lowerCAmelCase__	       =     self.char_decode
																					lowerCAmelCase__	       =     1
																					lowerCAmelCase__	       =     "[s]"
														elif format == DecodeType.BPE:
																					lowerCAmelCase__	       =     self.bpe_decode
																					lowerCAmelCase__	       =     2
																					lowerCAmelCase__	       =     "#"
														elif format == DecodeType.WORDPIECE:
																					lowerCAmelCase__	       =     self.wp_decode
																					lowerCAmelCase__	       =     1_02
																					lowerCAmelCase__	       =     "[SEP]"
														else:
																					raise ValueError(F"""Format {format} is not supported."""       )

														lowerCAmelCase__	       =     [], []
														lowerCAmelCase__	       =     pred_logits.size(0       )
														lowerCAmelCase__	       =     pred_logits.size(1       )
														lowerCAmelCase__	       =     pred_logits.topk(1 ,   dim=-1 ,   largest=_snake_case ,   sorted=_snake_case       )
														lowerCAmelCase__	       =     preds_index.view(-1 ,   _snake_case       )[:, 1:]
														lowerCAmelCase__	       =     decoder(_snake_case       )
														lowerCAmelCase__	       =     torch.nn.functional.softmax(_snake_case ,   dim=2       ).max(dim=2       )
														lowerCAmelCase__	       =     preds_max_prob[:, 1:]

														for index in range(_snake_case       ):
																					lowerCAmelCase__	       =     preds_str[index].find(_snake_case       )
																					lowerCAmelCase__	       =     preds_str[index][:pred_eos]
																					lowerCAmelCase__	       =     preds_index[index].cpu().tolist()
																					lowerCAmelCase__	       =     pred_index.index(_snake_case       ) if eos_token in pred_index else -1
																					lowerCAmelCase__	       =     preds_max_prob[index][: pred_eos_index + 1]
																					lowerCAmelCase__	       =     pred_max_prob.cumprod(dim=0       )[-1] if pred_max_prob.nelement() != 0 else 0.0
																					dec_strs.append(_snake_case       )
																					conf_scores.append(_snake_case       )

														return dec_strs, conf_scores







							def   __SCREAMING_SNAKE_CASE							(		self ,   lowerCamelCase_       )	->							Union[str, Any]:
														lowerCAmelCase__	       =     [seq.replace(''' ''' ,   ''''''       ) for seq in self.char_tokenizer.batch_decode(_snake_case       )]
														return decode_strs







							def   __SCREAMING_SNAKE_CASE							(		self ,   lowerCamelCase_       )	->							Optional[Any]:
														return self.bpe_tokenizer.batch_decode(_snake_case       )







							def   __SCREAMING_SNAKE_CASE							(		self ,   lowerCamelCase_       )	->							Optional[int]:
														lowerCAmelCase__	       =     [seq.replace(''' ''' ,   ''''''       ) for seq in self.wp_tokenizer.batch_decode(_snake_case       )]
														return decode_strs





'''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 		a__    (							a__    ,    unittest.TestCase  ):





							'''simple docstring'''






							lowercase__      :       List[Any]     						=				CLIPTokenizer
							lowercase__      :       List[str]     						=				CLIPTokenizerFast
							lowercase__      :       Dict     						=				True
							lowercase__      :       Any     						=				{}
							lowercase__      :       Optional[int]     						=				False







							def   __SCREAMING_SNAKE_CASE							(		self       )	->							Any:
														super().setUp()

														# fmt: off
														lowerCAmelCase__	       =     ['''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
														lowerCAmelCase__	       =     dict(zip(lowerCamelCase_ ,   range(len(lowerCamelCase_       )       )       )       )
														lowerCAmelCase__	       =     ['''#version: 0.2''', '''l o''', '''lo w</w>''', '''e r</w>''']
														lowerCAmelCase__	       =     {'''unk_token''': '''<unk>'''}

														lowerCAmelCase__	       =     os.path.join(self.tmpdirname ,   VOCAB_FILES_NAMES['''vocab_file''']       )
														lowerCAmelCase__	       =     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   __SCREAMING_SNAKE_CASE							(		self ,   **lowerCamelCase_       )	->							Any:
														kwargs.update(self.special_tokens_map       )
														return CLIPTokenizer.from_pretrained(self.tmpdirname ,   **lowerCamelCase_       )







							def   __SCREAMING_SNAKE_CASE							(		self ,   **lowerCamelCase_       )	->							int:
														kwargs.update(self.special_tokens_map       )
														return CLIPTokenizerFast.from_pretrained(self.tmpdirname ,   **lowerCamelCase_       )







							def   __SCREAMING_SNAKE_CASE							(		self ,   lowerCamelCase_       )	->							Any:
														lowerCAmelCase__	       =     '''lower newer'''
														lowerCAmelCase__	       =     '''lower newer'''
														return input_text, output_text







							def   __SCREAMING_SNAKE_CASE							(		self       )	->							Union[str, Any]:
														lowerCAmelCase__	       =     CLIPTokenizer(self.vocab_file ,   self.merges_file ,   **self.special_tokens_map       )
														lowerCAmelCase__	       =     '''lower newer'''
														lowerCAmelCase__	       =     ['''lo''', '''w''', '''er</w>''', '''n''', '''e''', '''w''', '''er</w>''']
														lowerCAmelCase__	       =     tokenizer.tokenize(lowerCamelCase_       )
														self.assertListEqual(lowerCamelCase_ ,   lowerCamelCase_       )

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







							@require_ftfy
							def   __SCREAMING_SNAKE_CASE							(		self       )	->							Tuple:
														for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
																					with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})"""       ):
																												lowerCAmelCase__	       =     self.tokenizer_class.from_pretrained(lowerCamelCase_ ,   **lowerCamelCase_       )
																												lowerCAmelCase__	       =     self.rust_tokenizer_class.from_pretrained(lowerCamelCase_ ,   **lowerCamelCase_       )

																												lowerCAmelCase__	       =     '''A\n\'ll 11p223RF☆ho!!to?\'d\'d\'\'d of a cat to-$\'\'d.'''
																												lowerCAmelCase__	       =     tokenizer_s.tokenize(lowerCamelCase_       )
																												lowerCAmelCase__	       =     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
																												lowerCAmelCase__	       =     '''xa\u0303y''' + ''' ''' + '''x\xe3y'''
																												lowerCAmelCase__	       =     tokenizer_s.tokenize(lowerCamelCase_       )
																												lowerCAmelCase__	       =     tokenizer_r.tokenize(lowerCamelCase_       )

																												self.assertListEqual(lowerCamelCase_ ,   lowerCamelCase_       )

																												# Test that the tokenization is identical on unicode of space type
																												lowerCAmelCase__	       =     [
																												    '''\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:
																																			lowerCAmelCase__	       =     tokenizer_s.tokenize(lowerCamelCase_       )
																																			lowerCAmelCase__	       =     tokenizer_r.tokenize(lowerCamelCase_       )

																																			self.assertListEqual(lowerCamelCase_ ,   lowerCamelCase_       )

																												# Test that the tokenization is identical on unicode of line break type
																												lowerCAmelCase__	       =     [
																												    '''\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:
																																			lowerCAmelCase__	       =     tokenizer_s.tokenize(lowerCamelCase_       )
																																			lowerCAmelCase__	       =     tokenizer_r.tokenize(lowerCamelCase_       )

																																			self.assertListEqual(lowerCamelCase_ ,   lowerCamelCase_       )







							def   __SCREAMING_SNAKE_CASE							(		self       )	->							str:
														# 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})"""       ):
																												lowerCAmelCase__	       =     '''hello'''  # `hello` is a token in the vocabulary of `pretrained_name`
																												lowerCAmelCase__	       =     F"""{text_of_1_token} {text_of_1_token}"""

																												lowerCAmelCase__	       =     self.rust_tokenizer_class.from_pretrained(
																												    lowerCamelCase_ ,   use_fast=lowerCamelCase_ ,   )
																												lowerCAmelCase__	       =     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_       )) ,   )

																												lowerCAmelCase__	       =     F""" {text}"""

																												lowerCAmelCase__	       =     self.rust_tokenizer_class.from_pretrained(
																												    lowerCamelCase_ ,   use_fast=lowerCamelCase_ ,   )
																												lowerCAmelCase__	       =     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   __SCREAMING_SNAKE_CASE							(		self       )	->							Union[str, Any]:
														# 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   __SCREAMING_SNAKE_CASE							(		self       )	->							List[Any]:
														super().test_tokenization_python_rust_equals()







							def   __SCREAMING_SNAKE_CASE							(		self       )	->							Any:
														# CLIP always lower cases letters
														pass