



'''simple docstring'''





def lowerCAmelCase    (__A    ,      __A = False):



     """simple docstring"""



     if n == 2:
          return True
     if not n % 2 or n < 2:
          return False
     if n > 5 and n % 10 not in (1, 3, 7, 9):  # can quickly check last digit
          return False
     if n > 3_317_044_064_679_887_385_961_981 and not allow_probable:
          raise ValueError(
              '''Warning: upper bound of deterministic test is exceeded. '''
              '''Pass allow_probable=True to allow probabilistic test. '''
              '''A return value of True indicates a probable prime.''')
     # array bounds provided by analysis
     _a           =    [
         2_047,
         1_373_653,
         25_326_001,
         3_215_031_751,
         2_152_302_898_747,
         3_474_749_660_383,
         341_550_071_728_321,
         1,
         3_825_123_056_546_413_051,
         1,
         1,
         318_665_857_834_031_151_167_461,
         3_317_044_064_679_887_385_961_981,
     ]

     _a           =    [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]
     for idx, _p in enumerate(__A    ,      1):
          if n < _p:
               # then we have our last prime to check
               _a           =    primes[:idx]
               break
     _a    ,       _a           =    n - 1, 0
     # break up n -1 into a power of 2 (s) and
     # remaining odd component
     # essentially, solve for d * 2 ** s == n - 1
     while d % 2 == 0:
          d //= 2
          s += 1
     for prime in plist:
          _a           =    False
          for r in range(__A):
               _a           =    pow(__A    ,      d * 2**r    ,      __A)
               # see article for analysis explanation for m
               if (r == 0 and m == 1) or ((m + 1) % n == 0):
                    _a           =    True
                    # this loop will not determine compositeness
                    break
          if pr:
               continue
          # if pr is False, then the above loop never evaluated to true,
          # and the n MUST be composite
          return False
     return True




def lowerCAmelCase    ():



     """simple docstring"""



     assert not miller_rabin(561)
     assert miller_rabin(563)
     # 2047

     assert not miller_rabin(838_201)
     assert miller_rabin(838_207)
     # 1_373_653

     assert not miller_rabin(17_316_001)
     assert miller_rabin(17_316_017)
     # 25_326_001

     assert not miller_rabin(3_078_386_641)
     assert miller_rabin(3_078_386_653)
     # 3_215_031_751

     assert not miller_rabin(1_713_045_574_801)
     assert miller_rabin(1_713_045_574_819)
     # 2_152_302_898_747

     assert not miller_rabin(2_779_799_728_307)
     assert miller_rabin(2_779_799_728_327)
     # 3_474_749_660_383

     assert not miller_rabin(113_850_023_909_441)
     assert miller_rabin(113_850_023_909_527)
     # 341_550_071_728_321

     assert not miller_rabin(1_275_041_018_848_804_351)
     assert miller_rabin(1_275_041_018_848_804_391)
     # 3_825_123_056_546_413_051

     assert not miller_rabin(79_666_464_458_507_787_791_867)
     assert miller_rabin(79_666_464_458_507_787_791_951)
     # 318_665_857_834_031_151_167_461

     assert not miller_rabin(552_840_677_446_647_897_660_333)
     assert miller_rabin(552_840_677_446_647_897_660_359)
     # 3_317_044_064_679_887_385_961_981
     # upper limit for probabilistic test


if __name__ == "__main__":
  test_miller_rabin()





"""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)





