


'''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': 20_48,
    'AI-Sweden/gpt-sw3-350m': 20_48,
    'AI-Sweden/gpt-sw3-1.6b': 20_48,
    'AI-Sweden/gpt-sw3-6.7b': 20_48,
    'AI-Sweden/gpt-sw3-20b': 20_48,
}


class 						_snake_case   (       a__		):
					lowerCAmelCase :List[Any]						=   VOCAB_FILES_NAMES
					lowerCAmelCase :Optional[Any]						=   PRETRAINED_VOCAB_FILES_MAP
					lowerCAmelCase :Union[str, Any]						=   PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
					lowerCAmelCase :Optional[Any]						=   ['''input_ids''', '''attention_mask''']




					def __init__( self							,							_lowerCamelCase							,							_lowerCamelCase=False							,							_lowerCamelCase=False							,							_lowerCamelCase=False							,							_lowerCamelCase=None							,							_lowerCamelCase=None							,							_lowerCamelCase=None							,							_lowerCamelCase=None							,							_lowerCamelCase = None							,							**_lowerCamelCase							,							):
								UpperCAmelCase__					:   int       				=       {} if sp_model_kwargs is None else sp_model_kwargs

								UpperCAmelCase__					:   Dict       				=       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""")
											UpperCAmelCase__					:   int       				=       """None"""

								# Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing
								UpperCAmelCase__					:   List[Any]       				=       """<|endoftext|>""" if eos_token is None else eos_token
								UpperCAmelCase__					:   Union[str, Any]       				=       """<unk>""" if unk_token is None else unk_token
								if "gpt-sw3-7b" in name_or_path:
											UpperCAmelCase__					:   str       				=       unk_token if pad_token is None else pad_token
											UpperCAmelCase__					:   Optional[Any]       				=       eos_token if bos_token is None else bos_token
								else:
											UpperCAmelCase__					:   Optional[int]       				=       """<pad>""" if pad_token is None else pad_token
											UpperCAmelCase__					:   List[Any]       				=       """<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							,							)

								UpperCAmelCase__					:   Optional[int]       				=       do_lower_case
								UpperCAmelCase__					:   Dict       				=       remove_space
								UpperCAmelCase__					:   Optional[Any]       				=       keep_accents
								UpperCAmelCase__					:   Tuple       				=       vocab_file

								UpperCAmelCase__					:   int       				=       spm.SentencePieceProcessor(**self.sp_model_kwargs)
								self.sp_model.Load(_lowerCamelCase)

								# Used for whitespace normalization in input texts
								# fmt : off
								UpperCAmelCase__					:   Optional[int]       				=       {""" """, """ """, """ """, """ """, """ """, """　""", """ """, """ """, """ """, """ """, """￼""", """"""}
								# fmt : on

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




					def __getstate__( self):
								UpperCAmelCase__					:   Optional[Any]       				=       self.__dict__.copy()
								UpperCAmelCase__					:   Optional[int]       				=       None
								return state




					def __setstate__( self							,							_lowerCamelCase):
								UpperCAmelCase__					:   int       				=       d

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

								UpperCAmelCase__					:   Any       				=       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 			snake_case__  ( self):
								return len(self.sp_model)




					def 			snake_case__  ( self							,							_lowerCamelCase):
								UpperCAmelCase__					:   Optional[int]       				=       self.non_printing_characters_re.sub(""""""							,							_lowerCamelCase)

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

								# NFC Unicode normalization
								UpperCAmelCase__					:   List[Any]       				=       unicodedata.normalize("""NFC"""							,							_lowerCamelCase)
								return text




					def 			snake_case__  ( self							,							_lowerCamelCase							,							**_lowerCamelCase):
								UpperCAmelCase__					:   Dict       				=       self.preprocess_text(_lowerCamelCase)
								return self.sp_model.encode(_lowerCamelCase							,							out_type=_lowerCamelCase)




					def 			snake_case__  ( self							,							_lowerCamelCase):
								return self.sp_model.PieceToId(_lowerCamelCase)




					def 			snake_case__  ( self							,							_lowerCamelCase):
								return self.sp_model.IdToPiece(_lowerCamelCase)




					@staticmethod
					def 			snake_case__  ( _lowerCamelCase):
								return out_string




					def 			snake_case__  ( self							,							_lowerCamelCase):
								UpperCAmelCase__					:   Optional[Any]       				=       []
								UpperCAmelCase__					:   int       				=       """"""
								UpperCAmelCase__					:   int       				=       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
														UpperCAmelCase__					:   Tuple       				=       True
														UpperCAmelCase__					:   int       				=       []
											else:
														current_sub_tokens.append(_lowerCamelCase)
														UpperCAmelCase__					:   Optional[Any]       				=       False
								out_string += self.sp_model.decode(_lowerCamelCase)

								return out_string




					def 			snake_case__  ( self):
								UpperCAmelCase__					:   List[Any]       				=       {self.convert_ids_to_tokens(_lowerCamelCase): i for i in range(self.vocab_size)}
								vocab.update(self.added_tokens_encoder)
								return vocab




					def 			snake_case__  ( self							,							_lowerCamelCase							,							_lowerCamelCase = None):
								if not os.path.isdir(_lowerCamelCase):
											logger.error(f'''Vocabulary path ({save_directory}) should be a directory''')
											return
								UpperCAmelCase__					:   Optional[int]       				=       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:
														UpperCAmelCase__					:   Optional[Any]       				=       self.sp_model.serialized_model_proto()
														fi.write(_lowerCamelCase)

								return (out_vocab_file,)




					def 			snake_case__  ( self							,							_lowerCamelCase							,							_lowerCamelCase = False):

								if isinstance(_lowerCamelCase							,							_lowerCamelCase):
											UpperCAmelCase__					:   List[str]       				=       self.preprocess_text(_lowerCamelCase)
											UpperCAmelCase__					:   Tuple       				=       self.sp_model.encode(_lowerCamelCase)
								else:
											UpperCAmelCase__					:   str       				=       [self.preprocess_text(_lowerCamelCase) for t in text]
											UpperCAmelCase__					:   Any       				=       self.sp_model.encode(_lowerCamelCase)

								if return_tensors is True or return_tensors == "pt":
											UpperCAmelCase__					:   Optional[Any]       				=       torch.tensor(_lowerCamelCase)

								return token_ids




					def 			snake_case__  ( self							,							_lowerCamelCase):
								return self.sp_model.decode(_lowerCamelCase)




					def 			snake_case__  ( self							,							_lowerCamelCase):
								UpperCAmelCase__					:   Tuple       				=       [f'''User: {text}''' if is_user else f'''Bot: {text}''' for is_user, text in conversation.iter_texts()]
								UpperCAmelCase__					:   Tuple       				=       (
								    f'''{self.eos_token}{self.bos_token}''' + f'''{self.bos_token}'''.join(_lowerCamelCase) + f'''{self.bos_token}Bot:'''
								)
								return self.encode(text=_lowerCamelCase)



'''simple docstring'''



from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


__A		={
    'configuration_table_transformer': [
        'TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'TableTransformerConfig',
        'TableTransformerOnnxConfig',
    ]
}

try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		__A		=[
		    'TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST',
		    'TableTransformerForObjectDetection',
		    'TableTransformerModel',
		    'TableTransformerPreTrainedModel',
		]


if TYPE_CHECKING:
		from .configuration_table_transformer import (
		    TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
		    TableTransformerConfig,
		    TableTransformerOnnxConfig,
		)

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_table_transformer import (
				    TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
				    TableTransformerForObjectDetection,
				    TableTransformerModel,
				    TableTransformerPreTrainedModel,
				)

else:
		import sys

		__A		=_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)