
import os
from shutil import copyfile
from typing import TYPE_CHECKING, Optional, Tuple

from tokenizers import processors

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging
from ...utils.versions import require_version


if TYPE_CHECKING:
		from transformers.pipelines.conversational import Conversation

require_version('''tokenizers>=0.13.3''')

if is_sentencepiece_available():
		from .tokenization_llama import LlamaTokenizer
else:
		A		:   Optional[int]         =    None

A		:   List[Any]         =    logging.get_logger(__name__)
A		:   Dict         =    {'vocab_file': 'tokenizer.model', 'tokenizer_file': 'tokenizer.json'}

A		:   str         =    '[INST]', '[/INST]'
A		:   Optional[Any]         =    '<<SYS>>\n', '\n<</SYS>>\n\n'

# fmt: off
A		:   Optional[int]         =    'You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your\\nanswers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\\nthat your responses are socially unbiased and positive in nature.\n\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not\\ncorrect. If you don\'t know the answer to a question, please don\'t share false information.'



class       a_   ( lowercase_						):
			a  : int				      =       VOCAB_FILES_NAMES
			a  : List[str]				      =       LlamaTokenizer
			a  : Tuple				      =       """left"""
			a  : int				      =       ["""input_ids""", """attention_mask"""]






			def __init__(			self							, __UpperCamelCase=None							, __UpperCamelCase=None							, __UpperCamelCase=False							, __UpperCamelCase="<unk>"							, __UpperCamelCase="<s>"							, __UpperCamelCase="</s>"							, __UpperCamelCase=True							, __UpperCamelCase=False							, **__UpperCamelCase							, ):
									super().__init__(
									    vocab_file=__UpperCamelCase							, tokenizer_file=__UpperCamelCase							, clean_up_tokenization_spaces=__UpperCamelCase							, unk_token=__UpperCamelCase							, bos_token=__UpperCamelCase							, eos_token=__UpperCamelCase							, **__UpperCamelCase							, )
									_lowercase									=				add_bos_token
									_lowercase									=				add_eos_token
									self.update_post_processor()

									_lowercase									=				vocab_file
									_lowercase									=				False if not self.vocab_file else True






			def       UpperCamelCase_							(			self     ):
									_lowercase									=				self.bos_token
									_lowercase									=				self.bos_token_id

									_lowercase									=				self.eos_token
									_lowercase									=				self.eos_token_id

									_lowercase									=				f"""{(bos+":0 ") * self.add_bos_token}$A:0{(" "+eos+":0") * self.add_eos_token}"""
									_lowercase									=				f"""{single}{(" "+bos+":1") * self.add_bos_token} $B:1{(" "+eos+":1") * self.add_eos_token}"""

									_lowercase									=				[]
									if self.add_bos_token:
															special_tokens.append((bos, bos_token_id)     )
									if self.add_eos_token:
															special_tokens.append((eos, eos_token_id)     )
									_lowercase									=				processors.TemplateProcessing(
									    single=__UpperCamelCase							, pair=__UpperCamelCase							, special_tokens=__UpperCamelCase     )






			@property
			def       UpperCamelCase_							(			self     ):
									return self._add_eos_token






			@property
			def       UpperCamelCase_							(			self     ):
									return self._add_bos_token






			@add_eos_token.setter
			def       UpperCamelCase_							(			self							, __UpperCamelCase     ):
									_lowercase									=				value
									self.update_post_processor()






			@add_bos_token.setter
			def       UpperCamelCase_							(			self							, __UpperCamelCase     ):
									_lowercase									=				value
									self.update_post_processor()






			def       UpperCamelCase_							(			self							, __UpperCamelCase							, __UpperCamelCase = None     ):







									if not self.can_save_slow_tokenizer:
															raise ValueError(
															    """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """
															    """tokenizer."""     )

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

									if os.path.abspath(self.vocab_file     ) != os.path.abspath(__UpperCamelCase     ):
															copyfile(self.vocab_file							, __UpperCamelCase     )

									return (out_vocab_file,)






			def       UpperCamelCase_							(			self							, __UpperCamelCase     ):
									_lowercase									=				list(conversation.iter_texts()     )
									if not all([is_user for is_user, msg in dialogue[::2]]     ) or not all(
									    [not is_user for is_user, msg in dialogue[1::2]]     ):
															raise ValueError(
															    """The model only supports \'user\' and \'assistant\' roles, starting with user and alternating (u/a/u/a/u...)"""     )

									_lowercase									=				[]
									if len(conversation.past_user_inputs     ) > 0:
															if not conversation.past_user_inputs[0].startswith(__UpperCamelCase     ) or E_SYS not in conversation.past_user_inputs[0]:
																					_lowercase									=				(
																					    B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.past_user_inputs[0]
																					)
									elif not dialogue[0][1].startswith(__UpperCamelCase     ) or E_SYS not in dialogue[0][1]:
															_lowercase									=				(dialogue[0][0], B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + dialogue[0][1])

									dialog_tokens += sum(
									    [
									        [self.bos_token_id]
									        + self.encode(
									            f"""{B_INST} {(prompt[1]).strip()} {E_INST} {(answer[1]).strip()} """							, add_special_tokens=__UpperCamelCase     )
									        + [self.eos_token_id]
									        for prompt, answer in zip(dialogue[::2]							, dialogue[1::2]     )
									    ]							, []							, )
									if not (dialogue[-1][0]):
															raise ValueError(f"""Last message must be from user, got {dialogue[-1]["role"]}"""     )
									dialog_tokens += [self.bos_token_id] + self.encode(
									    f"""{B_INST} {(dialogue[-1][1]).strip()} {E_INST}"""							, add_special_tokens=__UpperCamelCase     )
									return dialog_tokens






from ...configuration_utils import PretrainedConfig
from ...utils import logging


A		:   List[Any]         =    logging.get_logger(__name__)

A		:   str         =    {
    '''MCG-NJU/videomae-base''': '''https://huggingface.co/MCG-NJU/videomae-base/resolve/main/config.json''',
}



class       a_   ( _a						):
			a  : str				      =       '''videomae'''






			def __init__(			self							, __UpperCamelCase=224							, __UpperCamelCase=16							, __UpperCamelCase=3							, __UpperCamelCase=16							, __UpperCamelCase=2							, __UpperCamelCase=768							, __UpperCamelCase=12							, __UpperCamelCase=12							, __UpperCamelCase=3_072							, __UpperCamelCase="gelu"							, __UpperCamelCase=0.0							, __UpperCamelCase=0.0							, __UpperCamelCase=0.02							, __UpperCamelCase=1E-12							, __UpperCamelCase=True							, __UpperCamelCase=True							, __UpperCamelCase=6							, __UpperCamelCase=384							, __UpperCamelCase=4							, __UpperCamelCase=1_536							, __UpperCamelCase=True							, **__UpperCamelCase							, ):
									super().__init__(**__UpperCamelCase     )

									_lowercase									=				image_size
									_lowercase									=				patch_size
									_lowercase									=				num_channels
									_lowercase									=				num_frames
									_lowercase									=				tubelet_size

									_lowercase									=				hidden_size
									_lowercase									=				num_hidden_layers
									_lowercase									=				num_attention_heads
									_lowercase									=				intermediate_size
									_lowercase									=				hidden_act
									_lowercase									=				hidden_dropout_prob
									_lowercase									=				attention_probs_dropout_prob
									_lowercase									=				initializer_range
									_lowercase									=				layer_norm_eps
									_lowercase									=				qkv_bias
									_lowercase									=				use_mean_pooling

									_lowercase									=				decoder_num_attention_heads
									_lowercase									=				decoder_hidden_size
									_lowercase									=				decoder_num_hidden_layers
									_lowercase									=				decoder_intermediate_size
									_lowercase									=				norm_pix_loss