


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

import sentencepiece as spm

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


if TYPE_CHECKING:
    from transformers.pipelines.conversational import Conversation

__snake_case             =	logging.get_logger(__name__)

__snake_case             =	{'''vocab_file''': '''tokenizer.model'''}

__snake_case             =	{
    '''vocab_file''': {
        '''hf-internal-testing/llama-tokenizer''': '''https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer.model''',
    },
    '''tokenizer_file''': {
        '''hf-internal-testing/llama-tokenizer''': '''https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer_config.json''',
    },
}
__snake_case             =	{
    '''hf-internal-testing/llama-tokenizer''': 2_0_4_8,
}
__snake_case             =	'''▁'''

__snake_case       ,  __snake_case             =	'''[INST]''', '''[/INST]'''
__snake_case       ,  __snake_case             =	'''<<SYS>>\n''', '''\n<</SYS>>\n\n'''

# fmt: off
__snake_case             =	'''You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your\
answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\
that your responses are socially unbiased and positive in nature.

If a question does not make any sense, or is not factually coherent, explain why instead of answering something not\
correct. If you don\'t know the answer to a question, please don\'t share false information.'''



class   __lowerCamelCase (_a	):
       _lowercase       							=    VOCAB_FILES_NAMES
       _lowercase       							=    PRETRAINED_VOCAB_FILES_MAP
       _lowercase       							=    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       _lowercase       							=    ["""input_ids""", """attention_mask"""]







       def __init__( self:   int,A_:   Union[str, Any],A_:   Optional[Any]="<unk>",A_:   int="<s>",A_:   str="</s>",A_:   List[Any]=None,A_:   Optional[Dict[str, Any]] = None,A_:   List[Any]=True,A_:   List[Any]=False,A_:   List[Any]=False,A_:   List[str]=True,**A_:   Any,):






            '''simple docstring'''




            __UpperCamelCase   = {} if sp_model_kwargs is None else sp_model_kwargs
            __UpperCamelCase   = AddedToken(A_,lstrip=A_,rstrip=A_				) if isinstance(A_,A_				) else bos_token
            __UpperCamelCase   = AddedToken(A_,lstrip=A_,rstrip=A_				) if isinstance(A_,A_				) else eos_token
            __UpperCamelCase   = AddedToken(A_,lstrip=A_,rstrip=A_				) if isinstance(A_,A_				) else unk_token
            __UpperCamelCase   = AddedToken(A_,lstrip=A_,rstrip=A_				) if isinstance(A_,A_				) else pad_token
            super().__init__(
                bos_token=A_,eos_token=A_,unk_token=A_,pad_token=A_,add_bos_token=A_,add_eos_token=A_,sp_model_kwargs=self.sp_model_kwargs,clean_up_tokenization_spaces=A_,legacy=A_,**A_,)
            if legacy:
                 logger.warning_once(
                     F'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to'''
                     ' read the related pull request available at https://github.com/huggingface/transformers/pull/24565'				)
            __UpperCamelCase   = legacy
            __UpperCamelCase   = vocab_file
            __UpperCamelCase   = add_bos_token
            __UpperCamelCase   = add_eos_token
            __UpperCamelCase   = spm.SentencePieceProcessor(**self.sp_model_kwargs				)
            self.sp_model.Load(A_				)







       def __getstate__( self:   List[Any]				):






            '''simple docstring'''




            __UpperCamelCase   = self.__dict__.copy()
            __UpperCamelCase   = None
            __UpperCamelCase   = self.sp_model.serialized_model_proto()
            return state







       def __setstate__( self:   str,A_:   Dict				):






            '''simple docstring'''




            __UpperCamelCase   = d
            __UpperCamelCase   = spm.SentencePieceProcessor(**self.sp_model_kwargs				)
            self.sp_model.LoadFromSerializedProto(self.sp_model_proto				)







       @property
       def 		snake_case_  ( self:   Optional[Any]				):






            '''simple docstring'''




            return self.sp_model.get_piece_size()







       def 		snake_case_  ( self:   Any				):






            '''simple docstring'''




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







       def 		snake_case_  ( self:   Optional[int],A_:   Union[str, Any],**A_:   List[str]				):






            '''simple docstring'''




            if not self.legacy:
                 __UpperCamelCase   = SPIECE_UNDERLINE + text.replace(A_,' '				)
            return super().tokenize(A_,**A_				)







       def 		snake_case_  ( self:   Optional[int],A_:   int				):






            '''simple docstring'''




            if not self.legacy:
                 __UpperCamelCase   = text.startswith(A_				)
                 if is_first:
                      __UpperCamelCase   = text[1:]

            __UpperCamelCase   = self.sp_model.encode(A_,out_type=A_				)

            if not self.legacy and not is_first and not text.startswith(' '				) and tokens[0].startswith(A_				):
                 __UpperCamelCase   = ([tokens[0][1:]] if len(tokens[0]				) > 1 else []) + tokens[1:]
            return tokens







       def 		snake_case_  ( self:   List[Any],A_:   List[Any]				):






            '''simple docstring'''




            return self.sp_model.piece_to_id(A_				)







       def 		snake_case_  ( self:   int,A_:   List[str]				):






            '''simple docstring'''




            __UpperCamelCase   = self.sp_model.IdToPiece(A_				)
            return token







       def 		snake_case_  ( self:   Tuple,A_:   Tuple				):






            '''simple docstring'''




            __UpperCamelCase   = []
            __UpperCamelCase   = ''
            __UpperCamelCase   = False
            for i, token in enumerate(A_				):
                 # make sure that special tokens are not decoded using sentencepiece model
                 if token in self.all_special_tokens:
                      if not prev_is_special and i != 0:
                           out_string += " "
                      out_string += self.sp_model.decode(A_				) + token
                      __UpperCamelCase   = True
                      __UpperCamelCase   = []
                 else:
                      current_sub_tokens.append(A_				)
                      __UpperCamelCase   = False
            out_string += self.sp_model.decode(A_				)
            return out_string







       def 		snake_case_  ( self:   Optional[int],A_:   Optional[Any],A_:   Optional[str] = None				):






            '''simple docstring'''




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

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

            return (out_vocab_file,)







       def 		snake_case_  ( self:   Optional[int],A_:   int,A_:   Union[str, Any]=None				):






            '''simple docstring'''




            __UpperCamelCase   = [self.bos_token_id] if self.add_bos_token else []
            __UpperCamelCase   = [self.eos_token_id] if self.add_eos_token else []

            __UpperCamelCase   = bos_token_id + token_ids_a + eos_token_id

            if token_ids_a is not None:
                 __UpperCamelCase   = output + bos_token_id + token_ids_a + eos_token_id

            return output







       def 		snake_case_  ( self:   List[Any],A_:   List[int],A_:   Optional[List[int]] = None,A_:   bool = False				):






            '''simple docstring'''




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

            __UpperCamelCase   = [1] if self.add_bos_token else []
            __UpperCamelCase   = [1] if self.add_eos_token else []

            if token_ids_a is None:
                 return bos_token_id + ([0] * len(A_				)) + eos_token_id
            return (
                bos_token_id
                + ([0] * len(A_				))
                + eos_token_id
                + bos_token_id
                + ([0] * len(A_				))
                + eos_token_id
            )







       def 		snake_case_  ( self:   Union[str, Any],A_:   List[int],A_:   Optional[List[int]] = None				):






            '''simple docstring'''




            __UpperCamelCase   = [self.bos_token_id] if self.add_bos_token else []
            __UpperCamelCase   = [self.eos_token_id] if self.add_eos_token else []

            __UpperCamelCase   = [0] * len(bos_token_id + token_ids_a + eos_token_id				)

            if token_ids_a is not None:
                 output += [1] * len(bos_token_id + token_ids_a + eos_token_id				)

            return output







       def 		snake_case_  ( self:   Any,A_:   "Conversation"				):






            '''simple docstring'''




            __UpperCamelCase   = 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...)'				)

            __UpperCamelCase   = []
            if len(conversation.past_user_inputs				) > 0:
                 if not conversation.past_user_inputs[0].startswith(A_				) or E_SYS not in conversation.past_user_inputs[0]:
                      __UpperCamelCase   = (
                          B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.past_user_inputs[0]
                      )
            elif not dialogue[0][1].startswith(A_				) or E_SYS not in dialogue[0][1]:
                 __UpperCamelCase   = (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=A_				)
                    + [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=A_				)
            return dialog_tokens






import jax
import jax.numpy as jnp
from bigbird_flax import FlaxBigBirdForNaturalQuestions
from datasets import load_from_disk

from transformers import BigBirdTokenizerFast


__snake_case             =	{0: '''null''', 1: '''short''', 2: '''long''', 3: '''yes''', 4: '''no'''}
__snake_case             =	set(''''''.join(['''‘''', '''’''', '''´''', '''`''', '''.''', ''',''', '''-''', '''"''']))






def 		_A		(		_lowercase				,     _lowercase=0				,     _lowercase=None   )				->   Union[str, Any]:


     """simple docstring"""


     return [" ".join(x.split(' '   )[begin:end]   ) for x in answers if len(x.split(' '   )   ) > 1]






def 		_A		(		_lowercase				,     _lowercase=False   )				->   Tuple:


     """simple docstring"""


     if make_sub_answers:
          # if answers are longer than one word, make sure a predictions is correct if it coresponds to the complete 1: or :-1 sub word
          # *e.g.* if the correct answer contains a prefix such as "the", or "a"
          __UpperCamelCase   = (
              given_answers + get_sub_answers(_lowercase				,     begin=1   ) + get_sub_answers(_lowercase				,     end=-1   )
          )
     __UpperCamelCase   = []
     for answer in given_answers:
          __UpperCamelCase   = answer.replace('_'				,     ' '   ).lower()
          __UpperCamelCase   = ''.join(c if c not in PUNCTUATION_SET_TO_EXCLUDE else ' ' for c in alias   )
          answers.append(' '.join(alias.split()   ).strip()   )
     return set(_lowercase   )






def 		_A		(		_lowercase				,     _lowercase				,     _lowercase=1				,     _lowercase=1_00   )				->   Any:


     """simple docstring"""


     __UpperCamelCase,						__UpperCamelCase   = jax.lax.top_k(_lowercase				,     _lowercase   )
     __UpperCamelCase,						__UpperCamelCase   = jax.lax.top_k(_lowercase				,     _lowercase   )

     __UpperCamelCase   = best_end_idx[:, None] - best_start_idx[None, :]
     __UpperCamelCase   = jnp.logical_or(widths < 0				,     widths > max_size   )
     __UpperCamelCase   = (best_end_scores[:, None] + best_start_scores[None, :]) - (1e8 * mask)
     __UpperCamelCase   = jnp.argmax(_lowercase   ).item()

     return best_start_idx[best_score % top_k], best_end_idx[best_score // top_k]






def 		_A		(		_lowercase   )				->   List[str]:


     """simple docstring"""


     __UpperCamelCase   = sample['question']['text']
     __UpperCamelCase   = sample['document']['tokens']['token']
     __UpperCamelCase   = sample['document']['tokens']['is_html']
     __UpperCamelCase   = sample['annotations']['long_answer']
     __UpperCamelCase   = sample['annotations']['short_answers']

     __UpperCamelCase   = ' '.join([context[i] for i in range(len(_lowercase   )   ) if not is_html[i]]   )

     # 0 - No ; 1 - Yes
     for answer in sample["annotations"]["yes_no_answer"]:
          if answer == 0 or answer == 1:
               return {
                   "question": question,
                   "context": context_string,
                   "short": [],
                   "long": [],
                   "category": "no" if answer == 0 else "yes",
               }

     __UpperCamelCase   = []
     for s in short_answers:
          short_targets.extend(s['text']   )
     __UpperCamelCase   = list(set(_lowercase   )   )

     __UpperCamelCase   = []
     for s in long_answers:
          if s["start_token"] == -1:
               continue
          __UpperCamelCase   = context[s['start_token'] : s['end_token']]
          __UpperCamelCase   = is_html[s['start_token'] : s['end_token']]
          __UpperCamelCase   = ' '.join([answer[i] for i in range(len(_lowercase   )   ) if not html[i]]   )
          if new_answer not in long_targets:
               long_targets.append(_lowercase   )

     __UpperCamelCase   = 'long_short' if len(short_targets + long_targets   ) > 0 else 'null'

     return {
         "question": question,
         "context": context_string,
         "short": short_targets,
         "long": long_targets,
         "category": category,
     }






def 		_A		(		)				->   Optional[int]:


     """simple docstring"""


     __UpperCamelCase   = load_from_disk('natural-questions-validation'   )
     __UpperCamelCase   = dataset.map(_lowercase   ).remove_columns(['annotations', 'document', 'id']   )
     print(_lowercase   )

     __UpperCamelCase   = dataset.filter(lambda _lowercase   : (len(x['question']   ) + len(x['context']   )) < 4 * 40_96   )
     __UpperCamelCase   = short_validation_dataset.filter(lambda _lowercase   : x["category"] != "null"   )
     short_validation_dataset

     __UpperCamelCase   = 'vasudevgupta/flax-bigbird-natural-questions'
     __UpperCamelCase   = FlaxBigBirdForNaturalQuestions.from_pretrained(_lowercase   )
     __UpperCamelCase   = BigBirdTokenizerFast.from_pretrained(_lowercase   )

     @jax.jit
     def forward(*_lowercase				,     **_lowercase   ):
          __UpperCamelCase,						__UpperCamelCase,						__UpperCamelCase   = model(*_lowercase				,     **_lowercase   )
          return start_logits, end_logits, jnp.argmax(_lowercase				,     axis=-1   )

     def evaluate(_lowercase   ):
          # encode question and context so that they are separated by a tokenizer.sep_token and cut at max_length
          __UpperCamelCase   = tokenizer(
              example['question']				,     example['context']				,     return_tensors='np'				,     max_length=40_96				,     padding='max_length'				,     truncation=_lowercase				,     )

          __UpperCamelCase,						__UpperCamelCase,						__UpperCamelCase   = forward(**_lowercase   )

          __UpperCamelCase   = CATEGORY_MAPPING[category.item()]

          __UpperCamelCase   = example['long'] + example['short']
          if example["category"] in ["yes", "no", "null"]:
               __UpperCamelCase   = [example['category']]
          __UpperCamelCase   = example['category'] != 'null'
          # Now target can be: "yes", "no", "null", "list of long & short answers"

          if predicted_category in ["yes", "no", "null"]:
               __UpperCamelCase   = [predicted_category]
               __UpperCamelCase   = example['output'] == example['targets']
               __UpperCamelCase   = predicted_category != 'null'
               return example

          __UpperCamelCase   = 38 if predicted_category == 'short' else 10_24
          __UpperCamelCase,						__UpperCamelCase   = get_best_valid_start_end_idx(
              start_scores[0]				,     end_scores[0]				,     top_k=8				,     max_size=_lowercase   )

          __UpperCamelCase   = inputs['input_ids'][0].tolist()
          __UpperCamelCase   = [tokenizer.decode(input_ids[start_score : end_score + 1]   )]

          __UpperCamelCase   = expand_to_aliases(example['targets']				,     make_sub_answers=_lowercase   )
          __UpperCamelCase   = expand_to_aliases(example['output']   )

          # some preprocessing to both prediction and answer
          __UpperCamelCase   = {''.join(a.split()   ) for a in answers}
          __UpperCamelCase   = {''.join(p.split()   ) for p in predictions}
          __UpperCamelCase   = {s for s in predictions if s not in ['``', '\'\'', '`', '\'']}

          # if there is a common element, it's a exact match
          __UpperCamelCase   = len(list(answers & predictions   )   ) > 0
          __UpperCamelCase   = predicted_category != 'null' and len(_lowercase   ) > 0

          return example

     __UpperCamelCase   = short_validation_dataset.map(_lowercase   )

     __UpperCamelCase   = len(_lowercase   )
     __UpperCamelCase   = len(short_validation_dataset.filter(lambda _lowercase   : x["match"] == 1   )   )
     print('EM score:'				,     (matched / total) * 1_00				,     '%'   )


if __name__ == "__main__":
    main()


