



import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


__UpperCAmelCase			  =			logging.get_logger(__name__)

__UpperCAmelCase			  =			{
    '''microsoft/unispeech-large-1500h-cv''': (
        '''https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json'''
    ),
    # See all UniSpeech models at https://huggingface.co/models?filter=unispeech
}



class 							lowerCAmelCase_						(    a__				):
       UpperCAmelCase__							:   List[str]  	=    "unispeech"
       def __init__(     self,     SCREAMING_SNAKE_CASE_=32,     SCREAMING_SNAKE_CASE_=768,     SCREAMING_SNAKE_CASE_=12,     SCREAMING_SNAKE_CASE_=12,     SCREAMING_SNAKE_CASE_=3072,     SCREAMING_SNAKE_CASE_="gelu",     SCREAMING_SNAKE_CASE_=0.1,     SCREAMING_SNAKE_CASE_=0.1,     SCREAMING_SNAKE_CASE_=0.1,     SCREAMING_SNAKE_CASE_=0.0,     SCREAMING_SNAKE_CASE_=0.0,     SCREAMING_SNAKE_CASE_=0.1,     SCREAMING_SNAKE_CASE_=0.1,     SCREAMING_SNAKE_CASE_=0.02,     SCREAMING_SNAKE_CASE_=1e-5,     SCREAMING_SNAKE_CASE_="group",     SCREAMING_SNAKE_CASE_="gelu",     SCREAMING_SNAKE_CASE_=(512, 512, 512, 512, 512, 512, 512),     SCREAMING_SNAKE_CASE_=(5, 2, 2, 2, 2, 2, 2),     SCREAMING_SNAKE_CASE_=(10, 3, 3, 3, 3, 2, 2),     SCREAMING_SNAKE_CASE_=False,     SCREAMING_SNAKE_CASE_=128,     SCREAMING_SNAKE_CASE_=16,     SCREAMING_SNAKE_CASE_=False,     SCREAMING_SNAKE_CASE_=True,     SCREAMING_SNAKE_CASE_=0.05,     SCREAMING_SNAKE_CASE_=10,     SCREAMING_SNAKE_CASE_=2,     SCREAMING_SNAKE_CASE_=0.0,     SCREAMING_SNAKE_CASE_=10,     SCREAMING_SNAKE_CASE_=0,     SCREAMING_SNAKE_CASE_=320,     SCREAMING_SNAKE_CASE_=2,     SCREAMING_SNAKE_CASE_=0.1,     SCREAMING_SNAKE_CASE_=100,     SCREAMING_SNAKE_CASE_=256,     SCREAMING_SNAKE_CASE_=256,     SCREAMING_SNAKE_CASE_=0.1,     SCREAMING_SNAKE_CASE_="mean",     SCREAMING_SNAKE_CASE_=False,     SCREAMING_SNAKE_CASE_=False,     SCREAMING_SNAKE_CASE_=256,     SCREAMING_SNAKE_CASE_=80,     SCREAMING_SNAKE_CASE_=0,     SCREAMING_SNAKE_CASE_=1,     SCREAMING_SNAKE_CASE_=2,     SCREAMING_SNAKE_CASE_=0.5,     **SCREAMING_SNAKE_CASE_,     )	->						List[str]:
          super().__init__(**SCREAMING_SNAKE_CASE_,     pad_token_id=SCREAMING_SNAKE_CASE_,     bos_token_id=SCREAMING_SNAKE_CASE_,     eos_token_id=SCREAMING_SNAKE_CASE_			)
          UpperCamelCase       :    int		      =      hidden_size
          UpperCamelCase       :    Dict		      =      feat_extract_norm
          UpperCamelCase       :    Any		      =      feat_extract_activation
          UpperCamelCase       :    str		      =      list(SCREAMING_SNAKE_CASE_			)
          UpperCamelCase       :    Any		      =      list(SCREAMING_SNAKE_CASE_			)
          UpperCamelCase       :    int		      =      list(SCREAMING_SNAKE_CASE_			)
          UpperCamelCase       :    Tuple		      =      conv_bias
          UpperCamelCase       :    Union[str, Any]		      =      num_conv_pos_embeddings
          UpperCamelCase       :    Union[str, Any]		      =      num_conv_pos_embedding_groups
          UpperCamelCase       :    int		      =      len(self.conv_dim			)
          UpperCamelCase       :    str		      =      num_hidden_layers
          UpperCamelCase       :    List[Any]		      =      intermediate_size
          UpperCamelCase       :    List[str]		      =      hidden_act
          UpperCamelCase       :    str		      =      num_attention_heads
          UpperCamelCase       :    Dict		      =      hidden_dropout
          UpperCamelCase       :    Any		      =      attention_dropout
          UpperCamelCase       :    List[Any]		      =      activation_dropout
          UpperCamelCase       :    Any		      =      feat_proj_dropout
          UpperCamelCase       :    Tuple		      =      final_dropout
          UpperCamelCase       :    Optional[Any]		      =      layerdrop
          UpperCamelCase       :    Tuple		      =      layer_norm_eps
          UpperCamelCase       :    Tuple		      =      initializer_range
          UpperCamelCase       :    Optional[Any]		      =      num_ctc_classes
          UpperCamelCase       :    Any		      =      vocab_size
          UpperCamelCase       :    int		      =      do_stable_layer_norm
          UpperCamelCase       :    int		      =      use_weighted_layer_sum
          UpperCamelCase       :    Tuple		      =      classifier_proj_size

          if (
              (len(self.conv_stride			) != self.num_feat_extract_layers)
              or (len(self.conv_kernel			) != self.num_feat_extract_layers)
              or (len(self.conv_dim			) != self.num_feat_extract_layers)
          ):
             raise ValueError(
                 'Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =='
                 ' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ='
                 F""" {len(self.conv_dim			)}`, `len(config.conv_stride) = {len(self.conv_stride			)}`,"""
                 F""" `len(config.conv_kernel) = {len(self.conv_kernel			)}`."""			)

          # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
          UpperCamelCase       :    str		      =      apply_spec_augment
          UpperCamelCase       :    Optional[int]		      =      mask_time_prob
          UpperCamelCase       :    Any		      =      mask_time_length
          UpperCamelCase       :    Optional[Any]		      =      mask_time_min_masks
          UpperCamelCase       :    int		      =      mask_feature_prob
          UpperCamelCase       :    Union[str, Any]		      =      mask_feature_length
          UpperCamelCase       :    Optional[Any]		      =      mask_feature_min_masks

          # parameters for pretraining with codevector quantized representations
          UpperCamelCase       :    int		      =      num_codevectors_per_group
          UpperCamelCase       :    str		      =      num_codevector_groups
          UpperCamelCase       :    Optional[Any]		      =      contrastive_logits_temperature
          UpperCamelCase       :    Optional[Any]		      =      feat_quantizer_dropout
          UpperCamelCase       :    Union[str, Any]		      =      num_negatives
          UpperCamelCase       :    Dict		      =      codevector_dim
          UpperCamelCase       :    Tuple		      =      proj_codevector_dim
          UpperCamelCase       :    int		      =      diversity_loss_weight

          # ctc loss
          UpperCamelCase       :    int		      =      ctc_loss_reduction
          UpperCamelCase       :    str		      =      ctc_zero_infinity

          # pretraining loss
          UpperCamelCase       :    Dict		      =      replace_prob






       @property
       def    snake_case_			(     self			)	->						List[str]:
          return functools.reduce(operator.mul,     self.conv_stride,     1			)









import os

import jsonlines
import numpy as np
from tqdm import tqdm


UpperCAmelCase_		:					Dict          =  2048
UpperCAmelCase_		:					int          =  4096
UpperCAmelCase_		:					Any          =  42
UpperCAmelCase_		:					Optional[int]          =  os.environ.pop("PROCESS_TRAIN", "false")
UpperCAmelCase_		:					str          =  {"null": 0, "short": 1, "long": 2, "yes": 3, "no": 4}




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

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

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

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

				return answer




def 		lowerCAmelCase_ (						lowerCamelCase						,  lowerCamelCase=False ):
				__magic_name__						:						Optional[int]										=_get_single_answer(lowerCamelCase )
				# 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
								__magic_name__						:						Any										=example["""document"""]["""tokens"""]
								__magic_name__						:						str										=[]
								for i in range(len(doc["""token"""] ) ):
												if not doc["is_html"][i]:
																context.append(doc["""token"""][i] )
								return {
								    "context": " ".join(lowerCamelCase ),
								    "answer": {
								        "start_token": -100,  # ignore index in cross-entropy
								        "end_token": -100,  # 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

				__magic_name__						:						Dict										=["""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

				__magic_name__						:						Tuple										=example["""document"""]["""tokens"""]
				__magic_name__						:						Optional[int]										=answer["""start_token"""]
				__magic_name__						:						List[Any]										=answer["""end_token"""]

				__magic_name__						:						Optional[Any]										=[]
				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
				__magic_name__						:						Optional[int]										=""" """.join(context[start_token:end_token] )

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

				return {
				    "context": " ".join(lowerCamelCase ),
				    "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_ (						lowerCamelCase						,  lowerCamelCase						,  lowerCamelCase=2048						,  lowerCamelCase=4096						,  lowerCamelCase=True ):
				# overlap will be of doc_stride - q_len

				__magic_name__						:						Any										=get_context_and_ans(lowerCamelCase						,  assertion=lowerCamelCase )
				__magic_name__						:						Union[str, Any]										=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"],
								    },
								}

				__magic_name__						:						List[Any]										=tokenizer(example["""question"""]["""text"""]						,  out["""context"""] ).input_ids
				__magic_name__						:						Dict										=input_ids.index(tokenizer.sep_token_id ) + 1

				# return yes/no
				if answer["category"][0] in ["yes", "no"]:  # category is list with one element
								__magic_name__						:						List[str]										=[]
								__magic_name__						:						int										=[]
								__magic_name__						:						List[str]										=input_ids[:q_len]
								__magic_name__						:						Dict										=range(lowerCamelCase						,  len(lowerCamelCase )						,  max_length - doc_stride )
								for i in doc_start_indices:
												__magic_name__						:						List[Any]										=i + max_length - q_len
												__magic_name__						:						Tuple										=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": [-100] * len(lowerCamelCase ),
								        "end_token": [-100] * len(lowerCamelCase ),
								        "category": category,
								    },
								}

				__magic_name__						:						int										=out["""context"""].split()
				__magic_name__						:						Any										=splitted_context[answer["""end_token"""]]
				__magic_name__						:						str										=len(
				    tokenizer(
				        """ """.join(splitted_context[: answer["""start_token"""]] )						,  add_special_tokens=lowerCamelCase						,  ).input_ids )
				__magic_name__						:						Optional[int]										=len(
				    tokenizer(""" """.join(splitted_context[: answer["""end_token"""]] )						,  add_special_tokens=lowerCamelCase ).input_ids )

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

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

				__magic_name__						:						str										=input_ids[answer["""start_token"""] : answer["""end_token"""] + 1]  # right & left are inclusive
				__magic_name__						:						Dict										=answer["""start_token"""]
				__magic_name__						:						int										=answer["""end_token"""]

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

				if len(lowerCamelCase ) <= 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"],
								    },
								}

				__magic_name__						:						Any										=input_ids[:q_len]
				__magic_name__						:						Union[str, Any]										=range(lowerCamelCase						,  len(lowerCamelCase )						,  max_length - doc_stride )

				__magic_name__						:						Any										=[]
				__magic_name__						:						List[str]										=[]
				__magic_name__						:						List[str]										=[]
				__magic_name__						:						str										=[]  # null, yes, no, long, short
				for i in doc_start_indices:
								__magic_name__						:						List[Any]										=i + max_length - q_len
								__magic_name__						:						Dict										=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:
												__magic_name__						:						List[Any]										=start_token - i + q_len
												__magic_name__						:						Optional[Any]										=end_token - i + q_len
												answers_category.append(answer["""category"""][0] )  # ["short"] -> "short"
								else:
												__magic_name__						:						Optional[Any]										=-100
												__magic_name__						:						Optional[Any]										=-100
												answers_category.append("""null""" )
								__magic_name__						:						Optional[int]										=inputs[-1][start_token : end_token + 1]

								answers_start_token.append(lowerCamelCase )
								answers_end_token.append(lowerCamelCase )
								if assertion:
												if new != old and new != [tokenizer.cls_token_id]:
																print("""ISSUE in strided for ID:"""						,  example["""id"""] )
																print("""New:"""						,  tokenizer.decode(lowerCamelCase ) )
																print("""Old:"""						,  tokenizer.decode(lowerCamelCase )						,  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_ (						lowerCamelCase						,  lowerCamelCase						,  lowerCamelCase=2048						,  lowerCamelCase=4096						,  lowerCamelCase=False ):
				__magic_name__						:						List[Any]										=get_strided_contexts_and_ans(
				    lowerCamelCase						,  lowerCamelCase						,  doc_stride=lowerCamelCase						,  max_length=lowerCamelCase						,  assertion=lowerCamelCase						,  )

				return example




def 		lowerCAmelCase_ (						lowerCamelCase						,  lowerCamelCase ):
				with jsonlines.open(lowerCamelCase						,  """a""" ) as writer:
								for example in tqdm(lowerCamelCase						,  total=len(lowerCamelCase )						,  desc="""Saving samples ... """ ):
												__magic_name__						:						int										=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

							UpperCAmelCase_		:					Optional[int]          =  load_dataset("natural_questions")
							UpperCAmelCase_		:					Optional[int]          =  BigBirdTokenizer.from_pretrained("google/bigbird-roberta-base")

							UpperCAmelCase_		:					str          =  data["train" if PROCESS_TRAIN == "true" else "validation"]

							UpperCAmelCase_		:					Optional[int]          =  {
							    "tokenizer": tokenizer,
							    "doc_stride": DOC_STRIDE,
							    "max_length": MAX_LENGTH,
							    "assertion": False,
							}
							UpperCAmelCase_		:					int          =  data.map(prepare_inputs, fn_kwargs=fn_kwargs)
							UpperCAmelCase_		:					Optional[Any]          =  data.remove_columns(["annotations", "document", "id", "question"])
							print(data)

							np.random.seed(SEED)
							UpperCAmelCase_		:					int          =  "nq-training.jsonl" if PROCESS_TRAIN == "true" else "nq-validation.jsonl"
							save_to_disk(data, file_name=cache_file_name)




