




'''simple docstring'''







A   :  Optional[Any]       		=				{
    '''0000''': '''0''',
    '''0001''': '''1''',
    '''0010''': '''2''',
    '''0011''': '''3''',
    '''0100''': '''4''',
    '''0101''': '''5''',
    '''0110''': '''6''',
    '''0111''': '''7''',
    '''1000''': '''8''',
    '''1001''': '''9''',
    '''1010''': '''a''',
    '''1011''': '''b''',
    '''1100''': '''c''',
    '''1101''': '''d''',
    '''1110''': '''e''',
    '''1111''': '''f''',
}






def    lowerCAmelCase__ (       lowerCamelCase  :    str     ):
       _A  :			Union[str, Any]											=      str(lowerCamelCase     ).strip()

       # Exceptions
       if not binary_str:
              raise ValueError('Empty string was passed to the function'     )
       _A  :			Any											=      binary_str[0] == '-'
       _A  :			str											=      binary_str[1:] if is_negative else binary_str
       if not all(char in '01' for char in binary_str     ):
              raise ValueError('Non-binary value was passed to the function'     )

       _A  :			Optional[Any]											=      (
           '0' * (4 * (divmod(len(lowerCamelCase     )						,4     )[0] + 1) - len(lowerCamelCase     )) + binary_str
       )

       _A  :			Optional[int]											=      []
       for x in range(0						,len(lowerCamelCase     )						,4     ):
              hexadecimal.append(BITS_TO_HEX[binary_str[x : x + 4]]     )
       _A  :			int											=      '0x' + ''.join(lowerCamelCase     )

       return "-" + hexadecimal_str if is_negative else hexadecimal_str


if __name__ == "__main__":
   from doctest import testmod

   testmod()










'''simple docstring'''







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

from transformers import BigBirdTokenizerFast


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






def    lowerCAmelCase__ (       lowerCamelCase  :    str						,lowerCamelCase  :    Dict=0						,lowerCamelCase  :    List[Any]=None     ):
       return [" ".join(x.split(' '     )[begin:end]     ) for x in answers if len(x.split(' '     )     ) > 1]






def    lowerCAmelCase__ (       lowerCamelCase  :    Dict						,lowerCamelCase  :    Tuple=False     ):
       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"
              _A  :			str											=      (
                  given_answers + get_sub_answers(lowerCamelCase						,begin=1     ) + get_sub_answers(lowerCamelCase						,end=-1     )
              )
       _A  :			List[Any]											=      []
       for answer in given_answers:
              _A  :			List[str]											=      answer.replace('_'						,' '     ).lower()
              _A  :			Any											=      ''.join(c if c not in PUNCTUATION_SET_TO_EXCLUDE else ' ' for c in alias     )
              answers.append(' '.join(alias.split()     ).strip()     )
       return set(lowerCamelCase     )






def    lowerCAmelCase__ (       lowerCamelCase  :    List[Any]						,lowerCamelCase  :    Optional[int]						,lowerCamelCase  :    List[str]=1						,lowerCamelCase  :    Optional[int]=100     ):
       _A						,				_A  :			Dict											=      jax.lax.top_k(lowerCamelCase						,lowerCamelCase     )
       _A						,				_A  :			Dict											=      jax.lax.top_k(lowerCamelCase						,lowerCamelCase     )

       _A  :			List[str]											=      best_end_idx[:, None] - best_start_idx[None, :]
       _A  :			Any											=      jnp.logical_or(widths < 0						,widths > max_size     )
       _A  :			Any											=      (best_end_scores[:, None] + best_start_scores[None, :]) - (1E8 * mask)
       _A  :			List[Any]											=      jnp.argmax(lowerCamelCase     ).item()

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






def    lowerCAmelCase__ (       lowerCamelCase  :    Dict     ):
       _A  :			Optional[Any]											=      sample['question']['text']
       _A  :			Any											=      sample['document']['tokens']['token']
       _A  :			List[str]											=      sample['document']['tokens']['is_html']
       _A  :			str											=      sample['annotations']['long_answer']
       _A  :			int											=      sample['annotations']['short_answers']

       _A  :			Optional[int]											=      ' '.join([context[i] for i in range(len(lowerCamelCase     )     ) 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",
                     }

       _A  :			Tuple											=      []
       for s in short_answers:
              short_targets.extend(s['text']     )
       _A  :			Dict											=      list(set(lowerCamelCase     )     )

       _A  :			List[str]											=      []
       for s in long_answers:
              if s["start_token"] == -1:
                     continue
              _A  :			Tuple											=      context[s['start_token'] : s['end_token']]
              _A  :			Optional[Any]											=      is_html[s['start_token'] : s['end_token']]
              _A  :			Optional[int]											=      ' '.join([answer[i] for i in range(len(lowerCamelCase     )     ) if not html[i]]     )
              if new_answer not in long_targets:
                     long_targets.append(lowerCamelCase     )

       _A  :			List[str]											=      '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    lowerCAmelCase__ (       ):
       _A  :			Optional[Any]											=      load_from_disk('natural-questions-validation'     )
       _A  :			int											=      dataset.map(lowerCamelCase     ).remove_columns(['annotations', 'document', 'id']     )
       print(lowerCamelCase     )

       _A  :			int											=      dataset.filter(lambda lowerCamelCase     : (len(x['question']     ) + len(x['context']     )) < 4 * 4096     )
       _A  :			Dict											=      short_validation_dataset.filter(lambda lowerCamelCase     : x["category"] != "null"     )
       short_validation_dataset

       _A  :			Tuple											=      'vasudevgupta/flax-bigbird-natural-questions'
       _A  :			List[str]											=      FlaxBigBirdForNaturalQuestions.from_pretrained(lowerCamelCase     )
       _A  :			str											=      BigBirdTokenizerFast.from_pretrained(lowerCamelCase     )

       @jax.jit
       def forward(*lowerCamelCase  :    Optional[Any]						,**lowerCamelCase  :    Any     ):
              _A						,				_A						,				_A  :			Tuple											=      model(*lowerCamelCase						,**lowerCamelCase     )
              return start_logits, end_logits, jnp.argmax(lowerCamelCase						,axis=-1     )

       def evaluate(lowerCamelCase  :    Union[str, Any]     ):
              # encode question and context so that they are separated by a tokenizer.sep_token and cut at max_length
              _A  :			List[str]											=      tokenizer(
                  example['question']						,example['context']						,return_tensors='np'						,max_length=4096						,padding='max_length'						,truncation=lowerCamelCase						,)

              _A						,				_A						,				_A  :			Tuple											=      forward(**lowerCamelCase     )

              _A  :			List[Any]											=      CATEGORY_MAPPING[category.item()]

              _A  :			List[str]											=      example['long'] + example['short']
              if example["category"] in ["yes", "no", "null"]:
                     _A  :			Optional[int]											=      [example['category']]
              _A  :			List[Any]											=      example['category'] != 'null'
              # Now target can be: "yes", "no", "null", "list of long & short answers"

              if predicted_category in ["yes", "no", "null"]:
                     _A  :			Tuple											=      [predicted_category]
                     _A  :			Union[str, Any]											=      example['output'] == example['targets']
                     _A  :			Tuple											=      predicted_category != 'null'
                     return example

              _A  :			Dict											=      38 if predicted_category == 'short' else 1024
              _A						,				_A  :			List[Any]											=      get_best_valid_start_end_idx(
                  start_scores[0]						,end_scores[0]						,top_k=8						,max_size=lowerCamelCase     )

              _A  :			Optional[Any]											=      inputs['input_ids'][0].tolist()
              _A  :			Union[str, Any]											=      [tokenizer.decode(input_ids[start_score : end_score + 1]     )]

              _A  :			Union[str, Any]											=      expand_to_aliases(example['targets']						,make_sub_answers=lowerCamelCase     )
              _A  :			str											=      expand_to_aliases(example['output']     )

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

              # if there is a common element, it's a exact match
              _A  :			Tuple											=      len(list(answers & predictions     )     ) > 0
              _A  :			Any											=      predicted_category != 'null' and len(lowerCamelCase     ) > 0

              return example

       _A  :			str											=      short_validation_dataset.map(lowerCamelCase     )

       _A  :			Optional[int]											=      len(lowerCamelCase     )
       _A  :			str											=      len(short_validation_dataset.filter(lambda lowerCamelCase     : x["match"] == 1     )     )
       print('EM score:'						,(matched / total) * 100						,'%'     )


if __name__ == "__main__":
   main()






