





'''simple docstring'''

import os
import re
import unicodedata
from shutil import copyfile
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import is_torch_available, logging


if is_torch_available():
    import torch


if TYPE_CHECKING:
    from transformers.pipelines.conversational import Conversation


a   	=    logging.get_logger(__name__)
a   	=    {"vocab_file": "spiece.model"}

a   	=    {
    "vocab_file": {
        "AI-Sweden/gpt-sw3-126m": "https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model",
        "AI-Sweden/gpt-sw3-350m": "https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model",
        "AI-Sweden/gpt-sw3-1.6b": "https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model",
        "AI-Sweden/gpt-sw3-6.7b": "https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model",
        "AI-Sweden/gpt-sw3-20b": "https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model",
    }
}

a   	=    {
    "AI-Sweden/gpt-sw3-126m": 2048,
    "AI-Sweden/gpt-sw3-350m": 2048,
    "AI-Sweden/gpt-sw3-1.6b": 2048,
    "AI-Sweden/gpt-sw3-6.7b": 2048,
    "AI-Sweden/gpt-sw3-20b": 2048,
}







class __a			( _snake_case      ):
   __UpperCamelCase :			str						   =						VOCAB_FILES_NAMES
   __UpperCamelCase :			str						   =						PRETRAINED_VOCAB_FILES_MAP
   __UpperCamelCase :			List[Any]						   =						PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   __UpperCamelCase :			List[Any]						   =						['input_ids', 'attention_mask']





   def __init__(       self					:      Optional[Any]					,lowerCamelCase					:      Union[str, Any]					,lowerCamelCase					:      Optional[int]=False					,lowerCamelCase					:      List[str]=False					,lowerCamelCase					:      Any=False					,lowerCamelCase					:      List[str]=None					,lowerCamelCase					:      List[Any]=None					,lowerCamelCase					:      Dict=None					,lowerCamelCase					:      str=None					,lowerCamelCase					:      Optional[Dict[str, Any]] = None					,**lowerCamelCase					:      str					,):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							{} if sp_model_kwargs is None else sp_model_kwargs

      __SCREAMING_SNAKE_CASE   				=							kwargs.get("""name_or_path"""     )
      if name_or_path is None:
         logger.warning(
             """name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,"""
             """ you are testing the model, this can safely be ignored"""     )
         __SCREAMING_SNAKE_CASE   				=							"""None"""

      # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing
      __SCREAMING_SNAKE_CASE   				=							"""<|endoftext|>""" if eos_token is None else eos_token
      __SCREAMING_SNAKE_CASE   				=							"""<unk>""" if unk_token is None else unk_token
      if "gpt-sw3-7b" in name_or_path:
         __SCREAMING_SNAKE_CASE   				=							unk_token if pad_token is None else pad_token
         __SCREAMING_SNAKE_CASE   				=							eos_token if bos_token is None else bos_token
      else:
         __SCREAMING_SNAKE_CASE   				=							"""<pad>""" if pad_token is None else pad_token
         __SCREAMING_SNAKE_CASE   				=							"""<s>""" if bos_token is None else bos_token

      super().__init__(
          do_lower_case=lowerCamelCase					,remove_space=lowerCamelCase					,keep_accents=lowerCamelCase					,bos_token=lowerCamelCase					,eos_token=lowerCamelCase					,unk_token=lowerCamelCase					,pad_token=lowerCamelCase					,sp_model_kwargs=self.sp_model_kwargs					,**lowerCamelCase					,)

      __SCREAMING_SNAKE_CASE   				=							do_lower_case
      __SCREAMING_SNAKE_CASE   				=							remove_space
      __SCREAMING_SNAKE_CASE   				=							keep_accents
      __SCREAMING_SNAKE_CASE   				=							vocab_file

      __SCREAMING_SNAKE_CASE   				=							spm.SentencePieceProcessor(**self.sp_model_kwargs     )
      self.sp_model.Load(lowerCamelCase     )

      # Used for whitespace normalization in input texts
      # fmt : off
      __SCREAMING_SNAKE_CASE   				=							{""" """, """ """, """ """, """ """, """ """, """　""", """ """, """ """, """ """, """ """, """￼""", """"""}
      # fmt : on

      # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing
      __SCREAMING_SNAKE_CASE   				=							re.compile(
          f"""[{''.join(map(lowerCamelCase					,list(range(0					,9     )     ) + list(range(11					,32     )     ) + list(range(127					,160     )     ) + [160, 173, 8203]     )     )}]"""     )





   def __getstate__(       self					:      Any     ):

      '''simple docstring'''

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





   def __setstate__(       self					:      Union[str, Any]					,lowerCamelCase					:      Optional[int]     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							d

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

      __SCREAMING_SNAKE_CASE   				=							spm.SentencePieceProcessor(**self.sp_model_kwargs     )
      self.sp_model.Load(self.vocab_file     )





   @property
   # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size
   def   UpperCAmelCase__  (       self					:      int     ):

      '''simple docstring'''

      return len(self.sp_model     )





   def   UpperCAmelCase__  (       self					:      List[str]					,lowerCamelCase					:      str     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							self.non_printing_characters_re.sub(""""""					,lowerCamelCase     )

      # Normalize whitespaces
      __SCREAMING_SNAKE_CASE   				=							"""""".join([char if char not in self.whitespaces else """ """ for char in text]     )

      # NFC Unicode normalization
      __SCREAMING_SNAKE_CASE   				=							unicodedata.normalize("""NFC"""					,lowerCamelCase     )
      return text





   def   UpperCAmelCase__  (       self					:      List[Any]					,lowerCamelCase					:      str					,**lowerCamelCase					:      List[str]     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							self.preprocess_text(lowerCamelCase     )
      return self.sp_model.encode(lowerCamelCase					,out_type=lowerCamelCase     )





   def   UpperCAmelCase__  (       self					:      str					,lowerCamelCase					:      str     ):

      '''simple docstring'''

      return self.sp_model.PieceToId(lowerCamelCase     )





   def   UpperCAmelCase__  (       self					:      List[Any]					,lowerCamelCase					:      int     ):

      '''simple docstring'''

      return self.sp_model.IdToPiece(lowerCamelCase     )





   @staticmethod
   def   UpperCAmelCase__  (       lowerCamelCase					:      str     ):

      '''simple docstring'''

      return out_string





   def   UpperCAmelCase__  (       self					:      int					,lowerCamelCase					:      List[str]     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							[]
      __SCREAMING_SNAKE_CASE   				=							""""""
      __SCREAMING_SNAKE_CASE   				=							False
      for token in tokens:
         # make sure that special tokens are not decoded using sentencepiece model
         if token in self.all_special_tokens:
            # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document
            if not prev_is_special:
               out_string += " "

            out_string += self.sp_model.decode(lowerCamelCase     ) + token
            __SCREAMING_SNAKE_CASE   				=							True
            __SCREAMING_SNAKE_CASE   				=							[]
         else:
            current_sub_tokens.append(lowerCamelCase     )
            __SCREAMING_SNAKE_CASE   				=							False
      out_string += self.sp_model.decode(lowerCamelCase     )

      return out_string





   def   UpperCAmelCase__  (       self					:      List[str]     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							{self.convert_ids_to_tokens(lowerCamelCase     ): i for i in range(self.vocab_size     )}
      vocab.update(self.added_tokens_encoder     )
      return vocab





   def   UpperCAmelCase__  (       self					:      str					,lowerCamelCase					:      str					,lowerCamelCase					:      Optional[str] = None     ):

      '''simple docstring'''

      if not os.path.isdir(lowerCamelCase     ):
         logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""     )
         return
      __SCREAMING_SNAKE_CASE   				=							os.path.join(
          lowerCamelCase					,(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]     )

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

      return (out_vocab_file,)





   def   UpperCAmelCase__  (       self					:      str					,lowerCamelCase					:      Union[str, List[str]]					,lowerCamelCase					:      Union[str, bool] = False     ):

      '''simple docstring'''

      if isinstance(lowerCamelCase					,lowerCamelCase     ):
         __SCREAMING_SNAKE_CASE   				=							self.preprocess_text(lowerCamelCase     )
         __SCREAMING_SNAKE_CASE   				=							self.sp_model.encode(lowerCamelCase     )
      else:
         __SCREAMING_SNAKE_CASE   				=							[self.preprocess_text(lowerCamelCase     ) for t in text]
         __SCREAMING_SNAKE_CASE   				=							self.sp_model.encode(lowerCamelCase     )

      if return_tensors is True or return_tensors == "pt":
         __SCREAMING_SNAKE_CASE   				=							torch.tensor(lowerCamelCase     )

      return token_ids





   def   UpperCAmelCase__  (       self					:      Optional[Any]					,lowerCamelCase					:      Union[int, List[int]]     ):

      '''simple docstring'''

      return self.sp_model.decode(lowerCamelCase     )





   def   UpperCAmelCase__  (       self					:      Optional[int]					,lowerCamelCase					:      "Conversation"     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							[f"""User: {text}""" if is_user else f"""Bot: {text}""" for is_user, text in conversation.iter_texts()]
      __SCREAMING_SNAKE_CASE   				=							(
          f"""{self.eos_token}{self.bos_token}""" + f"""{self.bos_token}""".join(lowerCamelCase     ) + f"""{self.bos_token}Bot:"""
      )
      return self.encode(text=lowerCamelCase     )










from __future__ import annotations

import unittest

import numpy as np

from transformers import BlipTextConfig
from transformers.testing_utils import require_tf, slow
from transformers.utils import is_tf_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask


if is_tf_available():
							import tensorflow as tf

							from transformers import TFBlipTextModel
							from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST


class   __lowerCAmelCase  :
					"""simple docstring"""






					def __init__(  self       :							Dict					,       _snake_case       :							Union[str, Any]					,       _snake_case       :							Optional[Any]=12					,       _snake_case       :							Any=7					,       _snake_case       :							List[str]=True					,       _snake_case       :							int=True					,       _snake_case       :							int=True					,       _snake_case       :							Tuple=99					,       _snake_case       :							List[Any]=32					,       _snake_case       :							Optional[int]=32					,       _snake_case       :							List[str]=2					,       _snake_case       :							List[str]=4					,       _snake_case       :							List[Any]=37					,       _snake_case       :							Union[str, Any]=0.1					,       _snake_case       :							Tuple=0.1					,       _snake_case       :							Dict=5_12					,       _snake_case       :							Union[str, Any]=0.02					,       _snake_case       :							Any=0					,       _snake_case       :							Optional[Any]=None					,       ):






								"""simple docstring"""


								A__	  =     parent
								A__	  =     batch_size
								A__	  =     seq_length
								A__	  =     is_training
								A__	  =     use_input_mask
								A__	  =     use_labels
								A__	  =     vocab_size
								A__	  =     hidden_size
								A__	  =     projection_dim
								A__	  =     num_hidden_layers
								A__	  =     num_attention_heads
								A__	  =     intermediate_size
								A__	  =     dropout
								A__	  =     attention_dropout
								A__	  =     max_position_embeddings
								A__	  =     initializer_range
								A__	  =     scope
								A__	  =     bos_token_id



					def      _a				(  self       :							Optional[Any]       ):






								"""simple docstring"""


								A__	  =     ids_tensor([self.batch_size, self.seq_length]					,       self.vocab_size       )

								A__	  =     None
								if self.use_input_mask:
											A__	  =     random_attention_mask([self.batch_size, self.seq_length]       )

								if input_mask is not None:
											A__	  =     input_mask.numpy()
											A__  ,			A__	  =     input_mask.shape
											A__	  =     np.random.randint(1					,       seq_length - 1					,       size=(batch_size,)       )
											for batch_idx, start_index in enumerate(_snake_case       ):
														A__	  =     1
														A__	  =     0

								A__	  =     self.get_config()

								return config, input_ids, tf.convert_to_tensor(_snake_case       )



					def      _a				(  self       :							Tuple       ):






								"""simple docstring"""


								return BlipTextConfig(
								    vocab_size=self.vocab_size					,       hidden_size=self.hidden_size					,       projection_dim=self.projection_dim					,       num_hidden_layers=self.num_hidden_layers					,       num_attention_heads=self.num_attention_heads					,       intermediate_size=self.intermediate_size					,       dropout=self.dropout					,       attention_dropout=self.attention_dropout					,       max_position_embeddings=self.max_position_embeddings					,       initializer_range=self.initializer_range					,       bos_token_id=self.bos_token_id					,       )



					def      _a				(  self       :							int					,       _snake_case       :							Union[str, Any]					,       _snake_case       :							Any					,       _snake_case       :							List[str]       ):






								"""simple docstring"""


								A__	  =     TFBlipTextModel(config=_snake_case       )
								A__	  =     model(_snake_case					,       attention_mask=_snake_case					,       training=_snake_case       )
								A__	  =     model(_snake_case					,       training=_snake_case       )
								self.parent.assertEqual(result.last_hidden_state.shape					,       (self.batch_size, self.seq_length, self.hidden_size)       )
								self.parent.assertEqual(result.pooler_output.shape					,       (self.batch_size, self.hidden_size)       )



					def      _a				(  self       :							str       ):






								"""simple docstring"""


								A__	  =     self.prepare_config_and_inputs()
								A__  ,			A__  ,			A__	  =     config_and_inputs
								A__	  =     {'input_ids': input_ids, 'attention_mask': input_mask}
								return config, inputs_dict







@require_tf
class   __lowerCAmelCase  (		UpperCAmelCase_				,  unittest.TestCase   ):
					"""simple docstring"""






					A__					:		Tuple      							=     (TFBlipTextModel,) if is_tf_available() else ()
					A__					:		Optional[int]      							=     False
					A__					:		Union[str, Any]      							=     False
					A__					:		Union[str, Any]      							=     False



					def      _a				(  self       :							Any       ):






								"""simple docstring"""


								A__	  =     BlipTextModelTester(self       )
								A__	  =     ConfigTester(self					,       config_class=_snake_case					,       hidden_size=37       )



					def      _a				(  self       :							List[str]       ):






								"""simple docstring"""


								self.config_tester.run_common_tests()



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






								"""simple docstring"""


								A__	  =     self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*_snake_case       )



					def      _a				(  self       :							Tuple       ):






								"""simple docstring"""


								pass



					def      _a				(  self       :							int       ):






								"""simple docstring"""


								pass



					@unittest.skip(reason='Blip does not use inputs_embeds'       )
					def      _a				(  self       :							Any       ):






								"""simple docstring"""


								pass



					@unittest.skip(reason='BlipTextModel has no base class and is not available in MODEL_MAPPING'       )
					def      _a				(  self       :							str       ):






								"""simple docstring"""


								pass



					@unittest.skip(reason='BlipTextModel has no base class and is not available in MODEL_MAPPING'       )
					def      _a				(  self       :							Optional[Any]       ):






								"""simple docstring"""


								pass



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






								"""simple docstring"""


								for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											A__	  =     TFBlipTextModel.from_pretrained(_snake_case       )
											self.assertIsNotNone(_snake_case       )



					def      _a				(  self       :							int					,       _snake_case       :							int=True       ):






								"""simple docstring"""


								super().test_pt_tf_model_equivalence(allow_missing_keys=_snake_case       )




