
"""simple docstring"""






import json
import os
import unittest

from transformers import BatchEncoding, LEDTokenizer, LEDTokenizerFast
from transformers.models.led.tokenization_led import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers, require_torch
from transformers.utils import cached_property

from ...test_tokenization_common import TokenizerTesterMixin

@require_tokenizers
class 					__a     ( __a					,   unittest.TestCase       ):



							'''simple docstring'''







							_lowerCamelCase					:			List[Any]          =   LEDTokenizer
							_lowerCamelCase					:			List[Any]          =   LEDTokenizerFast
							_lowerCamelCase					:			int          =   True
							def   SCREAMING_SNAKE_CASE						(     self       )			->							List[Any]:




										'''simple docstring'''
										super().setUp()
										__lowercase       =       [
										    "l",
										    "o",
										    "w",
										    "e",
										    "r",
										    "s",
										    "t",
										    "i",
										    "d",
										    "n",
										    "\u0120",
										    "\u0120l",
										    "\u0120n",
										    "\u0120lo",
										    "\u0120low",
										    "er",
										    "\u0120lowest",
										    "\u0120newer",
										    "\u0120wider",
										    "<unk>",
										]
										__lowercase       =       dict(zip(_lowerCamelCase  ,    range(len(_lowerCamelCase       )       )       )       )
										__lowercase       =       ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""]
										__lowercase       =       {"unk_token": "<unk>"}

										__lowercase       =       os.path.join(self.tmpdirname  ,    VOCAB_FILES_NAMES["vocab_file"]       )
										__lowercase       =       os.path.join(self.tmpdirname  ,    VOCAB_FILES_NAMES["merges_file"]       )
										with open(self.vocab_file  ,    "w"  ,    encoding="utf-8"       ) as fp:
													fp.write(json.dumps(_lowerCamelCase       ) + "\n"       )
										with open(self.merges_file  ,    "w"  ,    encoding="utf-8"       ) as fp:
													fp.write("\n".join(_lowerCamelCase       )       )
							def   SCREAMING_SNAKE_CASE						(     self  ,    **_lowerCamelCase       )			->							List[str]:




										'''simple docstring'''
										kwargs.update(self.special_tokens_map       )
										return self.tokenizer_class.from_pretrained(self.tmpdirname  ,    **_lowerCamelCase       )
							def   SCREAMING_SNAKE_CASE						(     self  ,    **_lowerCamelCase       )			->							str:




										'''simple docstring'''
										kwargs.update(self.special_tokens_map       )
										return self.rust_tokenizer_class.from_pretrained(self.tmpdirname  ,    **_lowerCamelCase       )
							def   SCREAMING_SNAKE_CASE						(     self  ,    _lowerCamelCase       )			->							Union[str, Any]:




										'''simple docstring'''
										return "lower newer", "lower newer"
							@cached_property
							def   SCREAMING_SNAKE_CASE						(     self       )			->							str:




										'''simple docstring'''
										return LEDTokenizer.from_pretrained("allenai/led-base-16384"       )
							@cached_property
							def   SCREAMING_SNAKE_CASE						(     self       )			->							Dict:




										'''simple docstring'''
										return LEDTokenizerFast.from_pretrained("allenai/led-base-16384"       )
							@require_torch
							def   SCREAMING_SNAKE_CASE						(     self       )			->							List[Any]:




										'''simple docstring'''
										__lowercase       =       ["A long paragraph for summarization.", "Another paragraph for summarization."]
										__lowercase       =       [0, 250, 251, 17_818, 13, 39_186, 1_938, 4, 2]

										for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
													__lowercase       =       tokenizer(_lowerCamelCase  ,    max_length=len(_lowerCamelCase       )  ,    padding=_lowerCamelCase  ,    return_tensors="pt"       )
													self.assertIsInstance(_lowerCamelCase  ,    _lowerCamelCase       )

													self.assertEqual((2, 9)  ,    batch.input_ids.shape       )
													self.assertEqual((2, 9)  ,    batch.attention_mask.shape       )
													__lowercase       =       batch.input_ids.tolist()[0]
													self.assertListEqual(_lowerCamelCase  ,    _lowerCamelCase       )
							@require_torch
							def   SCREAMING_SNAKE_CASE						(     self       )			->							List[str]:




										'''simple docstring'''
										__lowercase       =       ["A long paragraph for summarization.", "Another paragraph for summarization."]
										for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
													__lowercase       =       tokenizer(_lowerCamelCase  ,    padding=_lowerCamelCase  ,    return_tensors="pt"       )
													self.assertIn("input_ids"  ,    _lowerCamelCase       )
													self.assertIn("attention_mask"  ,    _lowerCamelCase       )
													self.assertNotIn("labels"  ,    _lowerCamelCase       )
													self.assertNotIn("decoder_attention_mask"  ,    _lowerCamelCase       )
							@require_torch
							def   SCREAMING_SNAKE_CASE						(     self       )			->							List[Any]:




										'''simple docstring'''
										__lowercase       =       [
										    "Summary of the text.",
										    "Another summary.",
										]
										for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
													__lowercase       =       tokenizer(text_target=_lowerCamelCase  ,    max_length=32  ,    padding="max_length"  ,    return_tensors="pt"       )
													self.assertEqual(32  ,    targets["input_ids"].shape[1]       )
							@require_torch
							def   SCREAMING_SNAKE_CASE						(     self       )			->							List[str]:




										'''simple docstring'''
										for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
													__lowercase       =       tokenizer(
													    ["I am a small frog" * 1_024, "I am a small frog"]  ,    padding=_lowerCamelCase  ,    truncation=_lowerCamelCase  ,    return_tensors="pt"       )
													self.assertIsInstance(_lowerCamelCase  ,    _lowerCamelCase       )
													self.assertEqual(batch.input_ids.shape  ,    (2, 5_122)       )
							@require_torch
							def   SCREAMING_SNAKE_CASE						(     self       )			->							str:




										'''simple docstring'''
										__lowercase       =       ["A long paragraph for summarization."]
										__lowercase       =       [
										    "Summary of the text.",
										]
										for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
													__lowercase       =       tokenizer(_lowerCamelCase  ,    return_tensors="pt"       )
													__lowercase       =       tokenizer(text_target=_lowerCamelCase  ,    return_tensors="pt"       )
													__lowercase       =       inputs["input_ids"]
													__lowercase       =       targets["input_ids"]
													self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item()       )
													self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item()       )
													self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item()       )
													self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item()       )
							@require_torch
							def   SCREAMING_SNAKE_CASE						(     self       )			->							int:




										'''simple docstring'''
										for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
													__lowercase       =       ["Summary of the text.", "Another summary."]
													__lowercase       =       [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -1, -1]]

													__lowercase       =       tokenizer(_lowerCamelCase  ,    padding=_lowerCamelCase       )
													__lowercase       =       [[0] * len(_lowerCamelCase       ) for x in encoded_output["input_ids"]]
													__lowercase       =       tokenizer.pad(_lowerCamelCase       )
													self.assertSequenceEqual(outputs["global_attention_mask"]  ,    _lowerCamelCase       )
							def   SCREAMING_SNAKE_CASE						(     self       )			->							Optional[int]:




										'''simple docstring'''
										pass





							def   SCREAMING_SNAKE_CASE						(     self       )			->							Tuple:




										'''simple docstring'''
										for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
													with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})'''       ):
																__lowercase       =       self.rust_tokenizer_class.from_pretrained(_lowerCamelCase  ,    **_lowerCamelCase       )
																__lowercase       =       self.tokenizer_class.from_pretrained(_lowerCamelCase  ,    **_lowerCamelCase       )
																__lowercase       =       "A, <mask> AllenNLP sentence."
																__lowercase       =       tokenizer_r.encode_plus(_lowerCamelCase  ,    add_special_tokens=_lowerCamelCase  ,    return_token_type_ids=_lowerCamelCase       )
																__lowercase       =       tokenizer_p.encode_plus(_lowerCamelCase  ,    add_special_tokens=_lowerCamelCase  ,    return_token_type_ids=_lowerCamelCase       )
																self.assertEqual(sum(tokens_r["token_type_ids"]       )  ,    sum(tokens_p["token_type_ids"]       )       )
																self.assertEqual(
																    sum(tokens_r["attention_mask"]       ) / len(tokens_r["attention_mask"]       )  ,    sum(tokens_p["attention_mask"]       ) / len(tokens_p["attention_mask"]       )  ,    )

																__lowercase       =       tokenizer_r.convert_ids_to_tokens(tokens_r["input_ids"]       )
																__lowercase       =       tokenizer_p.convert_ids_to_tokens(tokens_p["input_ids"]       )
																self.assertSequenceEqual(tokens_p["input_ids"]  ,    [0, 250, 6, 50_264, 3_823, 487, 21_992, 3_645, 4, 2]       )
																self.assertSequenceEqual(tokens_r["input_ids"]  ,    [0, 250, 6, 50_264, 3_823, 487, 21_992, 3_645, 4, 2]       )

																self.assertSequenceEqual(
																    _lowerCamelCase  ,    ["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"]       )
																self.assertSequenceEqual(
																    _lowerCamelCase  ,    ["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"]       )







"""simple docstring"""






import os

import jsonlines
import numpy as np
from tqdm import tqdm


_lowercase							=				2_048
_lowercase							=				4_096
_lowercase							=				42
_lowercase							=				os.environ.pop('''PROCESS_TRAIN''', '''false''')
_lowercase							=				{'''null''': 0, '''short''': 1, '''long''': 2, '''yes''': 3, '''no''': 4}



def      lowerCAmelCase__			(		__magic_name__      )						->str:
			def choose_first(__magic_name__			,   __magic_name__=False      ):
						assert isinstance(__magic_name__			,   __magic_name__      )
						if len(__magic_name__      ) == 1:
									__lowercase       =       answer[0]
									return {k: [answer[k]] for k in answer} if is_long_answer else answer
						for a in answer:
									if is_long_answer:
												__lowercase       =       {k: [a[k]] for k in a}
									if len(a["start_token"]      ) > 0:
												break
						return a

			__lowercase       =       {"id": example["id"]}
			__lowercase       =       example["annotations"]
			__lowercase       =       annotation["yes_no_answer"]
			if 0 in yes_no_answer or 1 in yes_no_answer:
						__lowercase       =       ["yes"] if 1 in yes_no_answer else ["no"]
						__lowercase       =       __lowercase       =       []
						__lowercase       =       __lowercase       =       []
						__lowercase       =       ["<cls>"]
			else:
						__lowercase       =       ["short"]
						__lowercase       =       choose_first(annotation["short_answers"]      )
						if len(out["start_token"]      ) == 0:
									# answer will be long if short is not available
									__lowercase       =       ["long"]
									__lowercase       =       choose_first(annotation["long_answer"]			,   is_long_answer=__magic_name__      )
									__lowercase       =       []
						answer.update(__magic_name__      )

			# disregard some samples
			if len(answer["start_token"]      ) > 1 or answer["start_token"] == answer["end_token"]:
						__lowercase       =       True
			else:
						__lowercase       =       False

			__lowercase       =       ["start_token", "end_token", "start_byte", "end_byte", "text"]
			if not all(isinstance(answer[k]			,   __magic_name__      ) for k in cols      ):
						raise ValueError("Issue in ID"			,   example["id"]      )

			return answer



def      lowerCAmelCase__			(		__magic_name__			,   __magic_name__=False      )						->int:
			__lowercase       =       _get_single_answer(__magic_name__      )
			# bytes are of no use
			del answer["start_byte"]
			del answer["end_byte"]

			# handle yes_no answers explicitly
			if answer["category"][0] in ["yes", "no"]:  # category is list with one element
						__lowercase       =       example["document"]["tokens"]
						__lowercase       =       []
						for i in range(len(doc["token"]      )      ):
									if not doc["is_html"][i]:
												context.append(doc["token"][i]      )
						return {
						    "context": " ".join(__magic_name__      ),
						    "answer": {
						        "start_token": -1_0_0,  # ignore index in cross-entropy
						        "end_token": -1_0_0,  # ignore index in cross-entropy
						        "category": answer["category"],
						        "span": answer["category"],  # extra
						    },
						}

			# later, help in removing all no answers
			if answer["start_token"] == [-1]:
						return {
						    "context": "None",
						    "answer": {
						        "start_token": -1,
						        "end_token": -1,
						        "category": "null",
						        "span": "None",  # extra
						    },
						}

			# handling normal samples

			__lowercase       =       ["start_token", "end_token"]
			answer.update({k: answer[k][0] if len(answer[k]      ) > 0 else answer[k] for k in cols}      )  # e.g. [10] == 10

			__lowercase       =       example["document"]["tokens"]
			__lowercase       =       answer["start_token"]
			__lowercase       =       answer["end_token"]

			__lowercase       =       []
			for i in range(len(doc["token"]      )      ):
						if not doc["is_html"][i]:
									context.append(doc["token"][i]      )
						else:
									if answer["start_token"] > i:
												start_token -= 1
									if answer["end_token"] > i:
												end_token -= 1
			__lowercase       =       " ".join(context[start_token:end_token]      )

			# checking above code
			if assertion:
						__lowercase       =       doc["is_html"][answer["start_token"] : answer["end_token"]]
						__lowercase       =       doc["token"][answer["start_token"] : answer["end_token"]]
						__lowercase       =       " ".join([old[i] for i in range(len(__magic_name__      )      ) if not is_html[i]]      )
						if new != old:
									print("ID:"			,   example["id"]      )
									print("New:"			,   __magic_name__			,   end="\n"      )
									print("Old:"			,   __magic_name__			,   end="\n\n"      )

			return {
			    "context": " ".join(__magic_name__      ),
			    "answer": {
			        "start_token": start_token,
			        "end_token": end_token - 1,  # this makes it inclusive
			        "category": answer["category"],  # either long or short
			        "span": new,  # extra
			    },
			}



def      lowerCAmelCase__			(		__magic_name__			,   __magic_name__			,   __magic_name__=2_0_4_8			,   __magic_name__=4_0_9_6			,   __magic_name__=True      )						->Optional[Any]:
			# overlap will be of doc_stride - q_len

			__lowercase       =       get_context_and_ans(__magic_name__			,   assertion=__magic_name__      )
			__lowercase       =       out["answer"]

			# later, removing these samples
			if answer["start_token"] == -1:
						return {
						    "example_id": example["id"],
						    "input_ids": [[-1]],
						    "labels": {
						        "start_token": [-1],
						        "end_token": [-1],
						        "category": ["null"],
						    },
						}

			__lowercase       =       tokenizer(example["question"]["text"]			,   out["context"]      ).input_ids
			__lowercase       =       input_ids.index(tokenizer.sep_token_id      ) + 1

			# return yes/no
			if answer["category"][0] in ["yes", "no"]:  # category is list with one element
						__lowercase       =       []
						__lowercase       =       []
						__lowercase       =       input_ids[:q_len]
						__lowercase       =       range(__magic_name__			,   len(__magic_name__      )			,   max_length - doc_stride      )
						for i in doc_start_indices:
									__lowercase       =       i + max_length - q_len
									__lowercase       =       input_ids[i:end_index]
									inputs.append(q_indices + slice      )
									category.append(answer["category"][0]      )
									if slice[-1] == tokenizer.sep_token_id:
												break

						return {
						    "example_id": example["id"],
						    "input_ids": inputs,
						    "labels": {
						        "start_token": [-1_0_0] * len(__magic_name__      ),
						        "end_token": [-1_0_0] * len(__magic_name__      ),
						        "category": category,
						    },
						}

			__lowercase       =       out["context"].split()
			__lowercase       =       splitted_context[answer["end_token"]]
			__lowercase       =       len(
			    tokenizer(
			        " ".join(splitted_context[: answer["start_token"]]      )			,   add_special_tokens=__magic_name__			,   ).input_ids      )
			__lowercase       =       len(
			    tokenizer(" ".join(splitted_context[: answer["end_token"]]      )			,   add_special_tokens=__magic_name__      ).input_ids      )

			answer["start_token"] += q_len
			answer["end_token"] += q_len

			# fixing end token
			__lowercase       =       len(tokenizer(__magic_name__			,   add_special_tokens=__magic_name__      ).input_ids      )
			if num_sub_tokens > 1:
						answer["end_token"] += num_sub_tokens - 1

			__lowercase       =       input_ids[answer["start_token"] : answer["end_token"] + 1]  # right & left are inclusive
			__lowercase       =       answer["start_token"]
			__lowercase       =       answer["end_token"]

			if assertion:
						__lowercase       =       tokenizer.decode(__magic_name__      )
						if answer["span"] != new:
									print("ISSUE IN TOKENIZATION"      )
									print("OLD:"			,   answer["span"]      )
									print("NEW:"			,   __magic_name__			,   end="\n\n"      )

			if len(__magic_name__      ) <= max_length:
						return {
						    "example_id": example["id"],
						    "input_ids": [input_ids],
						    "labels": {
						        "start_token": [answer["start_token"]],
						        "end_token": [answer["end_token"]],
						        "category": answer["category"],
						    },
						}

			__lowercase       =       input_ids[:q_len]
			__lowercase       =       range(__magic_name__			,   len(__magic_name__      )			,   max_length - doc_stride      )

			__lowercase       =       []
			__lowercase       =       []
			__lowercase       =       []
			__lowercase       =       []  # null, yes, no, long, short
			for i in doc_start_indices:
						__lowercase       =       i + max_length - q_len
						__lowercase       =       input_ids[i:end_index]
						inputs.append(q_indices + slice      )
						assert len(inputs[-1]      ) <= max_length, "Issue in truncating length"

						if start_token >= i and end_token <= end_index - 1:
									__lowercase       =       start_token - i + q_len
									__lowercase       =       end_token - i + q_len
									answers_category.append(answer["category"][0]      )  # ["short"] -> "short"
						else:
									__lowercase       =       -1_0_0
									__lowercase       =       -1_0_0
									answers_category.append("null"      )
						__lowercase       =       inputs[-1][start_token : end_token + 1]

						answers_start_token.append(__magic_name__      )
						answers_end_token.append(__magic_name__      )
						if assertion:
									if new != old and new != [tokenizer.cls_token_id]:
												print("ISSUE in strided for ID:"			,   example["id"]      )
												print("New:"			,   tokenizer.decode(__magic_name__      )      )
												print("Old:"			,   tokenizer.decode(__magic_name__      )			,   end="\n\n"      )
						if slice[-1] == tokenizer.sep_token_id:
									break

			return {
			    "example_id": example["id"],
			    "input_ids": inputs,
			    "labels": {
			        "start_token": answers_start_token,
			        "end_token": answers_end_token,
			        "category": answers_category,
			    },
			}



def      lowerCAmelCase__			(		__magic_name__			,   __magic_name__			,   __magic_name__=2_0_4_8			,   __magic_name__=4_0_9_6			,   __magic_name__=False      )						->List[str]:
			__lowercase       =       get_strided_contexts_and_ans(
			    __magic_name__			,   __magic_name__			,   doc_stride=__magic_name__			,   max_length=__magic_name__			,   assertion=__magic_name__			,   )

			return example



def      lowerCAmelCase__			(		__magic_name__			,   __magic_name__      )						->Any:
			with jsonlines.open(__magic_name__			,   "a"      ) as writer:
						for example in tqdm(__magic_name__			,   total=len(__magic_name__      )			,   desc="Saving samples ... "      ):
									__lowercase       =       example["labels"]
									for ids, start, end, cat in zip(
									    example["input_ids"]			,   labels["start_token"]			,   labels["end_token"]			,   labels["category"]			,   ):
												if start == -1 and end == -1:
															continue  # leave waste samples with no answer
												if cat == "null" and np.random.rand() < 0.6:
															continue  # removing 50 % samples
												writer.write(
												    {
												        "input_ids": ids,
												        "start_token": start,
												        "end_token": end,
												        "category": CATEGORY_MAPPING[cat],
												    }      )


if __name__ == "__main__":
					from datasets import load_dataset

					from transformers import BigBirdTokenizer

					_lowercase							=				load_dataset('''natural_questions''')
					_lowercase							=				BigBirdTokenizer.from_pretrained('''google/bigbird-roberta-base''')

					_lowercase							=				data['''train''' if PROCESS_TRAIN == '''true''' else '''validation''']

					_lowercase							=				{
					    '''tokenizer''': tokenizer,
					    '''doc_stride''': DOC_STRIDE,
					    '''max_length''': MAX_LENGTH,
					    '''assertion''': False,
					}
					_lowercase							=				data.map(prepare_inputs, fn_kwargs=fn_kwargs)
					_lowercase							=				data.remove_columns(['''annotations''', '''document''', '''id''', '''question'''])
					print(data)

					np.random.seed(SEED)
					_lowercase							=				'''nq-training.jsonl''' if PROCESS_TRAIN == '''true''' else '''nq-validation.jsonl'''
					save_to_disk(data, file_name=cache_file_name)





