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




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


		'''simple docstring'''


		snake_case       ,snake_case   :    List[Any]			       =		jax.lax.top_k(UpperCamelCase__      ,    UpperCamelCase__       )
		snake_case       ,snake_case   :    str			       =		jax.lax.top_k(UpperCamelCase__      ,    UpperCamelCase__       )

		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   :    Dict			       =		jnp.argmax(UpperCamelCase__       ).item()

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




def 					_UpperCamelCase		(    SCREAMING_SNAKE_CASE__       )   ->				Tuple:


		'''simple docstring'''


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

		snake_case   :    Any			       =		''' '''.join([context[i] for i in range(len(UpperCamelCase__       )       ) 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   :    Any			       =		[]
		for s in short_answers:
				short_targets.extend(s['''text''']       )
		snake_case   :    Any			       =		list(set(UpperCamelCase__       )       )

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

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


		'''simple docstring'''


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

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

		snake_case   :    str			       =		'''vasudevgupta/flax-bigbird-natural-questions'''
		snake_case   :    Dict			       =		FlaxBigBirdForNaturalQuestions.from_pretrained(UpperCamelCase__       )
		snake_case   :    Union[str, Any]			       =		BigBirdTokenizerFast.from_pretrained(UpperCamelCase__       )

		@jax.jit
		def forward(*SCREAMING_SNAKE_CASE__      ,    **SCREAMING_SNAKE_CASE__       ):
				snake_case       ,snake_case       ,snake_case   :    Dict			       =		model(*UpperCamelCase__      ,    **UpperCamelCase__       )
				return start_logits, end_logits, jnp.argmax(UpperCamelCase__      ,    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   :    int			       =		tokenizer(
				    example['''question''']      ,    example['''context''']      ,    return_tensors='''np'''      ,    max_length=4096      ,    padding='''max_length'''      ,    truncation=UpperCamelCase__      ,    )

				snake_case       ,snake_case       ,snake_case   :    int			       =		forward(**UpperCamelCase__       )

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

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

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

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

				snake_case   :    Dict			       =		inputs['''input_ids'''][0].tolist()
				snake_case   :    Optional[int]			       =		[tokenizer.decode(input_ids[start_score : end_score + 1]       )]

				snake_case   :    str			       =		expand_to_aliases(example['''targets''']      ,    make_sub_answers=UpperCamelCase__       )
				snake_case   :    Tuple			       =		expand_to_aliases(example['''output''']       )

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

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

				return example

		snake_case   :    List[Any]			       =		short_validation_dataset.map(UpperCamelCase__       )

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


if __name__ == "__main__":
						main()









import unittest

from transformers import is_torch_available, load_tool

from .test_tools_common import ToolTesterMixin


if is_torch_available():
	import torch




class      UpperCamelCase_				(   unittest.TestCase ,     UpperCamelCase__			):


							def    _snake_case     (							self			:Dict						)      ->      Union[str, Any]:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=					load_tool("""speech-to-text"""						)
									self.tool.setup()


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



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=					self.tool(torch.ones(3000						)						)
									self.assertEqual(__A							, """ you"""						)


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



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=					self.tool(audio=torch.ones(3000						)						)
									self.assertEqual(__A							, """ you"""						)