
'''simple docstring'''
import jax
import jax.numpy as jnp
from bigbird_flax import FlaxBigBirdForNaturalQuestions
from datasets import load_from_disk

from transformers import BigBirdTokenizerFast


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




def 					_UpperCamelCase		(    SCREAMING_SNAKE_CASE__      ,    SCREAMING_SNAKE_CASE__=0      ,    SCREAMING_SNAKE_CASE__=None       )   ->				Optional[Any]:


		'''simple docstring'''


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




def 					_UpperCamelCase		(    SCREAMING_SNAKE_CASE__      ,    SCREAMING_SNAKE_CASE__=False       )   ->				Optional[int]:


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




def 					_UpperCamelCase		(    SCREAMING_SNAKE_CASE__      ,    SCREAMING_SNAKE_CASE__      ,    SCREAMING_SNAKE_CASE__=1      ,    SCREAMING_SNAKE_CASE__=100       )   ->				List[Any]:


		'''simple docstring'''


		snake_case       ,snake_case   :    int			       =		jax.lax.top_k(SCREAMING_SNAKE_CASE__      ,    SCREAMING_SNAKE_CASE__       )
		snake_case       ,snake_case   :    List[Any]			       =		jax.lax.top_k(SCREAMING_SNAKE_CASE__      ,    SCREAMING_SNAKE_CASE__       )

		snake_case   :    Dict			       =		best_end_idx[:, None] - best_start_idx[None, :]
		snake_case   :    str			       =		jnp.logical_or(widths < 0      ,    widths > max_size       )
		snake_case   :    str			       =		(best_end_scores[:, None] + best_start_scores[None, :]) - (1E8 * mask)
		snake_case   :    int			       =		jnp.argmax(SCREAMING_SNAKE_CASE__       ).item()

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




def 					_UpperCamelCase		(    SCREAMING_SNAKE_CASE__       )   ->				Optional[int]:


		'''simple docstring'''


		snake_case   :    str			       =		sample['''question''']['''text''']
		snake_case   :    Optional[int]			       =		sample['''document''']['''tokens''']['''token''']
		snake_case   :    Tuple			       =		sample['''document''']['''tokens''']['''is_html''']
		snake_case   :    Tuple			       =		sample['''annotations''']['''long_answer''']
		snake_case   :    Union[str, Any]			       =		sample['''annotations''']['''short_answers''']

		snake_case   :    List[Any]			       =		''' '''.join([context[i] for i in range(len(SCREAMING_SNAKE_CASE__       )       ) 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",
						}

		snake_case   :    Union[str, Any]			       =		[]
		for s in short_answers:
				short_targets.extend(s['''text''']       )
		snake_case   :    List[Any]			       =		list(set(SCREAMING_SNAKE_CASE__       )       )

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

		snake_case   :    Optional[int]			       =		'''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 					_UpperCamelCase		(    )   ->				Any:


		'''simple docstring'''


		snake_case   :    Union[str, Any]			       =		load_from_disk('''natural-questions-validation'''       )
		snake_case   :    Optional[int]			       =		dataset.map(SCREAMING_SNAKE_CASE__       ).remove_columns(['''annotations''', '''document''', '''id''']       )
		print(SCREAMING_SNAKE_CASE__       )

		snake_case   :    Union[str, Any]			       =		dataset.filter(lambda SCREAMING_SNAKE_CASE__       : (len(x['''question''']       ) + len(x['''context''']       )) < 4 * 4096       )
		snake_case   :    str			       =		short_validation_dataset.filter(lambda SCREAMING_SNAKE_CASE__       : x["category"] != "null"       )
		short_validation_dataset

		snake_case   :    int			       =		'''vasudevgupta/flax-bigbird-natural-questions'''
		snake_case   :    Optional[int]			       =		FlaxBigBirdForNaturalQuestions.from_pretrained(SCREAMING_SNAKE_CASE__       )
		snake_case   :    List[Any]			       =		BigBirdTokenizerFast.from_pretrained(SCREAMING_SNAKE_CASE__       )

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

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

				snake_case       ,snake_case       ,snake_case   :    Dict			       =		forward(**SCREAMING_SNAKE_CASE__       )

				snake_case   :    List[str]			       =		CATEGORY_MAPPING[category.item()]

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

				if predicted_category in ["yes", "no", "null"]:
						snake_case   :    Any			       =		[predicted_category]
						snake_case   :    Dict			       =		example['''output'''] == example['''targets''']
						snake_case   :    List[Any]			       =		predicted_category != '''null'''
						return example

				snake_case   :    Optional[Any]			       =		38 if predicted_category == '''short''' else 1024
				snake_case       ,snake_case   :    int			       =		get_best_valid_start_end_idx(
				    start_scores[0]      ,    end_scores[0]      ,    top_k=8      ,    max_size=SCREAMING_SNAKE_CASE__       )

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

				snake_case   :    List[Any]			       =		expand_to_aliases(example['''targets''']      ,    make_sub_answers=SCREAMING_SNAKE_CASE__       )
				snake_case   :    Tuple			       =		expand_to_aliases(example['''output''']       )

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

				# if there is a common element, it's a exact match
				snake_case   :    int			       =		len(list(answers & predictions       )       ) > 0
				snake_case   :    Optional[Any]			       =		predicted_category != '''null''' and len(SCREAMING_SNAKE_CASE__       ) > 0

				return example

		snake_case   :    Dict			       =		short_validation_dataset.map(SCREAMING_SNAKE_CASE__       )

		snake_case   :    List[str]			       =		len(SCREAMING_SNAKE_CASE__       )
		snake_case   :    List[Any]			       =		len(short_validation_dataset.filter(lambda SCREAMING_SNAKE_CASE__       : x["match"] == 1       )       )
		print('''EM score:'''      ,    (matched / total) * 100      ,    '''%'''       )


if __name__ == "__main__":
						main()




'''simple docstring'''
import json
import os
import shutil
import tempfile
import unittest

from transformers import is_speech_available, is_torch_available
from transformers.models.speechta import SpeechTaTokenizer
from transformers.testing_utils import get_tests_dir, require_torch
from transformers.utils import FEATURE_EXTRACTOR_NAME


if is_speech_available() and is_torch_available():
						from transformers import SpeechTaFeatureExtractor, SpeechTaProcessor

						from .test_feature_extraction_speechta import floats_list


lowercase__		    =	get_tests_dir("fixtures/test_sentencepiece_bpe_char.model")






@require_torch
class      snake_case__    (	unittest.TestCase ):







		"""simple docstring"""

		def 	lowerCAmelCase							(	self							:       Optional[Any]	)		->       Optional[int]:






				"""simple docstring"""







				snake_case   :    List[str]			       =		tempfile.mkdtemp()

				snake_case   :    Optional[int]			       =		SpeechTaTokenizer(UpperCamelCase__	)
				tokenizer.save_pretrained(self.tmpdirname	)

				snake_case   :    Any			       =		{
				    '''feature_size''': 1,
				    '''padding_value''': 0.0,
				    '''sampling_rate''': 1_6000,
				    '''do_normalize''': False,
				    '''num_mel_bins''': 80,
				    '''hop_length''': 16,
				    '''win_length''': 64,
				    '''win_function''': '''hann_window''',
				    '''fmin''': 80,
				    '''fmax''': 7600,
				    '''mel_floor''': 1e-1_0,
				    '''reduction_factor''': 2,
				    '''return_attention_mask''': True,
				}

				snake_case   :    Tuple			       =		os.path.join(self.tmpdirname   ,     UpperCamelCase__	)
				with open(self.feature_extraction_file   ,     '''w'''   ,     encoding='''utf-8'''	) as fp:
						fp.write(json.dumps(UpperCamelCase__	) + '''\n'''	)



		def 	lowerCAmelCase							(	self							:       Dict   ,     **UpperCamelCase__							:       Any	)		->       str:






				"""simple docstring"""







				return SpeechTaTokenizer.from_pretrained(self.tmpdirname   ,     **UpperCamelCase__	)



		def 	lowerCAmelCase							(	self							:       Union[str, Any]   ,     **UpperCamelCase__							:       int	)		->       Optional[Any]:






				"""simple docstring"""







				return SpeechTaFeatureExtractor.from_pretrained(self.tmpdirname   ,     **UpperCamelCase__	)



		def 	lowerCAmelCase							(	self							:       Any	)		->       Any:






				"""simple docstring"""







				shutil.rmtree(self.tmpdirname	)



		def 	lowerCAmelCase							(	self							:       Tuple	)		->       Dict:






				"""simple docstring"""







				snake_case   :    str			       =		self.get_tokenizer()
				snake_case   :    List[str]			       =		self.get_feature_extractor()

				snake_case   :    Dict			       =		SpeechTaProcessor(tokenizer=UpperCamelCase__   ,     feature_extractor=UpperCamelCase__	)

				processor.save_pretrained(self.tmpdirname	)
				snake_case   :    Dict			       =		SpeechTaProcessor.from_pretrained(self.tmpdirname	)

				self.assertEqual(processor.tokenizer.get_vocab()   ,     tokenizer.get_vocab()	)
				self.assertIsInstance(processor.tokenizer   ,     UpperCamelCase__	)

				self.assertEqual(processor.feature_extractor.to_json_string()   ,     feature_extractor.to_json_string()	)
				self.assertIsInstance(processor.feature_extractor   ,     UpperCamelCase__	)



		def 	lowerCAmelCase							(	self							:       str	)		->       Any:






				"""simple docstring"""







				snake_case   :    int			       =		SpeechTaProcessor(tokenizer=self.get_tokenizer()   ,     feature_extractor=self.get_feature_extractor()	)
				processor.save_pretrained(self.tmpdirname	)

				snake_case   :    int			       =		self.get_tokenizer(bos_token='''(BOS)'''   ,     eos_token='''(EOS)'''	)
				snake_case   :    str			       =		self.get_feature_extractor(do_normalize=UpperCamelCase__   ,     padding_value=1.0	)

				snake_case   :    Tuple			       =		SpeechTaProcessor.from_pretrained(
				    self.tmpdirname   ,     bos_token='''(BOS)'''   ,     eos_token='''(EOS)'''   ,     do_normalize=UpperCamelCase__   ,     padding_value=1.0	)

				self.assertEqual(processor.tokenizer.get_vocab()   ,     tokenizer_add_kwargs.get_vocab()	)
				self.assertIsInstance(processor.tokenizer   ,     UpperCamelCase__	)

				self.assertEqual(processor.feature_extractor.to_json_string()   ,     feature_extractor_add_kwargs.to_json_string()	)
				self.assertIsInstance(processor.feature_extractor   ,     UpperCamelCase__	)



		def 	lowerCAmelCase							(	self							:       Optional[Any]	)		->       Dict:






				"""simple docstring"""







				snake_case   :    List[Any]			       =		self.get_feature_extractor()
				snake_case   :    List[str]			       =		self.get_tokenizer()

				snake_case   :    Union[str, Any]			       =		SpeechTaProcessor(tokenizer=UpperCamelCase__   ,     feature_extractor=UpperCamelCase__	)

				snake_case   :    Union[str, Any]			       =		floats_list((3, 1000)	)

				snake_case   :    List[str]			       =		feature_extractor(audio=UpperCamelCase__   ,     return_tensors='''np'''	)
				snake_case   :    Any			       =		processor(audio=UpperCamelCase__   ,     return_tensors='''np'''	)

				for key in input_feat_extract.keys():
						self.assertAlmostEqual(input_feat_extract[key].sum()   ,     input_processor[key].sum()   ,     delta=1e-2	)



		def 	lowerCAmelCase							(	self							:       Dict	)		->       str:






				"""simple docstring"""







				snake_case   :    str			       =		self.get_feature_extractor()
				snake_case   :    Optional[int]			       =		self.get_tokenizer()

				snake_case   :    Union[str, Any]			       =		SpeechTaProcessor(tokenizer=UpperCamelCase__   ,     feature_extractor=UpperCamelCase__	)

				snake_case   :    Dict			       =		floats_list((3, 1000)	)

				snake_case   :    str			       =		feature_extractor(audio_target=UpperCamelCase__   ,     return_tensors='''np'''	)
				snake_case   :    List[Any]			       =		processor(audio_target=UpperCamelCase__   ,     return_tensors='''np'''	)

				for key in input_feat_extract.keys():
						self.assertAlmostEqual(input_feat_extract[key].sum()   ,     input_processor[key].sum()   ,     delta=1e-2	)



		def 	lowerCAmelCase							(	self							:       List[Any]	)		->       int:






				"""simple docstring"""







				snake_case   :    Optional[int]			       =		self.get_feature_extractor()
				snake_case   :    Union[str, Any]			       =		self.get_tokenizer()

				snake_case   :    List[str]			       =		SpeechTaProcessor(tokenizer=UpperCamelCase__   ,     feature_extractor=UpperCamelCase__	)

				snake_case   :    Optional[Any]			       =		'''This is a test string'''

				snake_case   :    Dict			       =		processor(text=UpperCamelCase__	)
				snake_case   :    List[str]			       =		tokenizer(UpperCamelCase__	)

				for key in encoded_tok.keys():
						self.assertListEqual(encoded_tok[key]   ,     encoded_processor[key]	)



		def 	lowerCAmelCase							(	self							:       Optional[Any]	)		->       Dict:






				"""simple docstring"""







				snake_case   :    Optional[int]			       =		self.get_feature_extractor()
				snake_case   :    str			       =		self.get_tokenizer()

				snake_case   :    str			       =		SpeechTaProcessor(tokenizer=UpperCamelCase__   ,     feature_extractor=UpperCamelCase__	)

				snake_case   :    Dict			       =		'''This is a test string'''

				snake_case   :    Any			       =		processor(text_target=UpperCamelCase__	)
				snake_case   :    List[str]			       =		tokenizer(UpperCamelCase__	)

				for key in encoded_tok.keys():
						self.assertListEqual(encoded_tok[key]   ,     encoded_processor[key]	)



		def 	lowerCAmelCase							(	self							:       str	)		->       Optional[int]:






				"""simple docstring"""







				snake_case   :    List[str]			       =		self.get_feature_extractor()
				snake_case   :    str			       =		self.get_tokenizer()

				snake_case   :    Optional[Any]			       =		SpeechTaProcessor(tokenizer=UpperCamelCase__   ,     feature_extractor=UpperCamelCase__	)

				snake_case   :    Optional[int]			       =		[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

				snake_case   :    List[str]			       =		processor.batch_decode(UpperCamelCase__	)
				snake_case   :    List[str]			       =		tokenizer.batch_decode(UpperCamelCase__	)

				self.assertListEqual(UpperCamelCase__   ,     UpperCamelCase__	)



		def 	lowerCAmelCase							(	self							:       Optional[Any]	)		->       Union[str, Any]:






				"""simple docstring"""







				snake_case   :    List[Any]			       =		self.get_feature_extractor()
				snake_case   :    Tuple			       =		self.get_tokenizer()

				snake_case   :    List[Any]			       =		SpeechTaProcessor(tokenizer=UpperCamelCase__   ,     feature_extractor=UpperCamelCase__	)

				self.assertListEqual(
				    processor.model_input_names   ,     feature_extractor.model_input_names   ,     msg='''`processor` and `feature_extractor` model input names do not match'''   ,     )


