



from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast
from ...utils import logging


if TYPE_CHECKING:
							from ...feature_extraction_utils import FeatureExtractionMixin
							from ...tokenization_utils_base import PreTrainedTokenizerBase
							from ...utils import TensorType

__snake_case    :		Optional[Any]  =logging.get_logger(__name__)

__snake_case    :		Optional[int]  ={
    'openai/whisper-base': 'https://huggingface.co/openai/whisper-base/resolve/main/config.json',
}

# fmt: off
__snake_case    :		List[str]  =[
    1, 2, 7, 8, 9, 1_0, 1_4, 2_5,
    2_6, 2_7, 2_8, 2_9, 3_1, 5_8, 5_9, 6_0, 6_1, 6_2,
    6_3, 9_0, 9_1, 9_2, 9_3, 3_5_7, 3_6_6, 4_3_8, 5_3_2, 6_8_5,
    7_0_5, 7_9_6, 9_3_0, 1_0_5_8, 1_2_2_0, 1_2_6_7, 1_2_7_9, 1_3_0_3, 1_3_4_3, 1_3_7_7,
    1_3_9_1, 1_6_3_5, 1_7_8_2, 1_8_7_5, 2_1_6_2, 2_3_6_1, 2_4_8_8, 3_4_6_7, 4_0_0_8, 4_2_1_1,
    4_6_0_0, 4_8_0_8, 5_2_9_9, 5_8_5_5, 6_3_2_9, 7_2_0_3, 9_6_0_9, 9_9_5_9, 1_0_5_6_3, 1_0_7_8_6,
    1_1_4_2_0, 1_1_7_0_9, 1_1_9_0_7, 1_3_1_6_3, 1_3_6_9_7, 1_3_7_0_0, 1_4_8_0_8, 1_5_3_0_6, 1_6_4_1_0, 1_6_7_9_1,
    1_7_9_9_2, 1_9_2_0_3, 1_9_5_1_0, 2_0_7_2_4, 2_2_3_0_5, 2_2_9_3_5, 2_7_0_0_7, 3_0_1_0_9, 3_0_4_2_0, 3_3_4_0_9,
    3_4_9_4_9, 4_0_2_8_3, 4_0_4_9_3, 4_0_5_4_9, 4_7_2_8_2, 4_9_1_4_6, 5_0_2_5_7, 5_0_3_5_9, 5_0_3_6_0, 5_0_3_6_1
]
__snake_case    :		Dict  =[
    1, 2, 7, 8, 9, 1_0, 1_4, 2_5,
    2_6, 2_7, 2_8, 2_9, 3_1, 5_8, 5_9, 6_0, 6_1, 6_2,
    6_3, 9_0, 9_1, 9_2, 9_3, 3_5_9, 5_0_3, 5_2_2, 5_4_2, 8_7_3,
    8_9_3, 9_0_2, 9_1_8, 9_2_2, 9_3_1, 1_3_5_0, 1_8_5_3, 1_9_8_2, 2_4_6_0, 2_6_2_7,
    3_2_4_6, 3_2_5_3, 3_2_6_8, 3_5_3_6, 3_8_4_6, 3_9_6_1, 4_1_8_3, 4_6_6_7, 6_5_8_5, 6_6_4_7,
    7_2_7_3, 9_0_6_1, 9_3_8_3, 1_0_4_2_8, 1_0_9_2_9, 1_1_9_3_8, 1_2_0_3_3, 1_2_3_3_1, 1_2_5_6_2, 1_3_7_9_3,
    1_4_1_5_7, 1_4_6_3_5, 1_5_2_6_5, 1_5_6_1_8, 1_6_5_5_3, 1_6_6_0_4, 1_8_3_6_2, 1_8_9_5_6, 2_0_0_7_5, 2_1_6_7_5,
    2_2_5_2_0, 2_6_1_3_0, 2_6_1_6_1, 2_6_4_3_5, 2_8_2_7_9, 2_9_4_6_4, 3_1_6_5_0, 3_2_3_0_2, 3_2_4_7_0, 3_6_8_6_5,
    4_2_8_6_3, 4_7_4_2_5, 4_9_8_7_0, 5_0_2_5_4, 5_0_2_5_8, 5_0_3_6_0, 5_0_3_6_1, 5_0_3_6_2
]



class 	lowerCamelCase__      (							lowerCamelCase__):




		'''simple docstring'''



		snake_case_     ="""whisper"""
		snake_case_     =["""past_key_values"""]
		snake_case_     ={"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""}



		def __init__(self		,__lowerCamelCase=5_18_65		,__lowerCamelCase=80		,__lowerCamelCase=6		,__lowerCamelCase=4		,__lowerCamelCase=6		,__lowerCamelCase=4		,__lowerCamelCase=15_36		,__lowerCamelCase=15_36		,__lowerCamelCase=0.0		,__lowerCamelCase=0.0		,__lowerCamelCase=5_02_57		,__lowerCamelCase=True		,__lowerCamelCase=True		,__lowerCamelCase="gelu"		,__lowerCamelCase=2_56		,__lowerCamelCase=0.0		,__lowerCamelCase=0.0		,__lowerCamelCase=0.0		,__lowerCamelCase=0.02		,__lowerCamelCase=False		,__lowerCamelCase=15_00		,__lowerCamelCase=4_48		,__lowerCamelCase=5_02_56		,__lowerCamelCase=5_02_56		,__lowerCamelCase=5_02_56		,__lowerCamelCase=None		,__lowerCamelCase=[2_20, 5_02_56]		,__lowerCamelCase=False		,__lowerCamelCase=2_56		,__lowerCamelCase=False		,__lowerCamelCase=0.05		,__lowerCamelCase=10		,__lowerCamelCase=2		,__lowerCamelCase=0.0		,__lowerCamelCase=10		,__lowerCamelCase=0		,__lowerCamelCase=7		,**__lowerCamelCase		,)					->      Dict:

						"""simple docstring"""






						lowerCAmelCase__					:    Union[str, Any]												=					vocab_size
						lowerCAmelCase__					:    Tuple												=					num_mel_bins
						lowerCAmelCase__					:    Optional[int]												=					d_model
						lowerCAmelCase__					:    str												=					encoder_layers
						lowerCAmelCase__					:    str												=					encoder_attention_heads
						lowerCAmelCase__					:    Optional[Any]												=					decoder_layers
						lowerCAmelCase__					:    Optional[int]												=					decoder_attention_heads
						lowerCAmelCase__					:    List[Any]												=					decoder_ffn_dim
						lowerCAmelCase__					:    int												=					encoder_ffn_dim
						lowerCAmelCase__					:    Dict												=					dropout
						lowerCAmelCase__					:    Any												=					attention_dropout
						lowerCAmelCase__					:    List[str]												=					activation_dropout
						lowerCAmelCase__					:    List[str]												=					activation_function
						lowerCAmelCase__					:    Optional[Any]												=					init_std
						lowerCAmelCase__					:    Any												=					encoder_layerdrop
						lowerCAmelCase__					:    int												=					decoder_layerdrop
						lowerCAmelCase__					:    Dict												=					use_cache
						lowerCAmelCase__					:    Union[str, Any]												=					encoder_layers
						lowerCAmelCase__					:    Optional[Any]												=					scale_embedding  # scale factor will be sqrt(d_model) if True
						lowerCAmelCase__					:    List[Any]												=					max_source_positions
						lowerCAmelCase__					:    List[str]												=					max_target_positions

						# Audio Classification-specific parameters. Feel free to ignore for other classes.
						lowerCAmelCase__					:    Any												=					classifier_proj_size
						lowerCAmelCase__					:    int												=					use_weighted_layer_sum

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

						lowerCAmelCase__					:    Any												=					median_filter_width

						super().__init__(
						    pad_token_id=snake_case__		,bos_token_id=snake_case__		,eos_token_id=snake_case__		,is_encoder_decoder=snake_case__		,decoder_start_token_id=snake_case__		,suppress_tokens=snake_case__		,begin_suppress_tokens=snake_case__		,**snake_case__		,)



class 	lowerCamelCase__      (							lowerCamelCase__):




		'''simple docstring'''



		@property
		def 		lowerCAmelCase__				(self			)					->      Mapping[str, Mapping[int, str]]:

						"""simple docstring"""






						lowerCAmelCase__					:    List[str]												=					OrderedDict(
						    [
						        ('''input_features''', {0: '''batch''', 1: '''feature_size''', 2: '''encoder_sequence'''}),
						    ]			)
						if self.use_past:
										lowerCAmelCase__					:    Tuple												=					{0: '''batch'''}
						else:
										lowerCAmelCase__					:    Optional[Any]												=					{0: '''batch''', 1: '''decoder_sequence'''}

						if self.use_past:
										self.fill_with_past_key_values_(snake_case__		,direction='''inputs'''			)

						return common_inputs



		def 		lowerCAmelCase__				(self		,__lowerCamelCase		,__lowerCamelCase = -1		,__lowerCamelCase = -1		,__lowerCamelCase = False		,__lowerCamelCase = None		,__lowerCamelCase = 2_20_50		,__lowerCamelCase = 5.0		,__lowerCamelCase = 2_20		,)					->      Mapping[str, Any]:

						"""simple docstring"""






						lowerCAmelCase__					:    List[Any]												=					OrderedDict()
						lowerCAmelCase__					:    Tuple												=					OnnxConfig.generate_dummy_inputs(
						    self		,preprocessor=preprocessor.feature_extractor		,batch_size=snake_case__		,framework=snake_case__		,sampling_rate=snake_case__		,time_duration=snake_case__		,frequency=snake_case__		,)
						lowerCAmelCase__					:    str												=					encoder_inputs['''input_features'''].shape[2]
						lowerCAmelCase__					:    str												=					encoder_sequence_length // 2 if self.use_past else seq_length

						lowerCAmelCase__					:    Union[str, Any]												=					super().generate_dummy_inputs(
						    preprocessor.tokenizer		,snake_case__		,snake_case__		,snake_case__		,snake_case__			)

						lowerCAmelCase__					:    Dict												=					encoder_inputs.pop('''input_features'''			)
						lowerCAmelCase__					:    Tuple												=					decoder_inputs.pop('''decoder_input_ids'''			)

						if "past_key_values" in decoder_inputs:
										lowerCAmelCase__					:    List[Any]												=					decoder_inputs.pop('''past_key_values'''			)

						return dummy_inputs



		@property
		def 		lowerCAmelCase__				(self			)					->      float:

						"""simple docstring"""






						return 1e-3






import itertools
import json
import linecache
import os
import pickle
import re
import socket
import string
from collections import Counter
from logging import getLogger
from pathlib import Path
from typing import Callable, Dict, Iterable, List

import git
import torch
from torch.utils.data import Dataset

from transformers import BartTokenizer, RagTokenizer, TaTokenizer






def      lowerCAmelCase__		(   lowerCamelCase_		:		int	,lowerCamelCase_		:		Optional[Any]	,lowerCamelCase_		:		Optional[int]	,lowerCamelCase_		:		Optional[int]	,lowerCamelCase_		:		Any=True	,lowerCamelCase_		:		Tuple="pt"):





				'''simple docstring'''

				lowerCAmelCase__					:    Tuple												=					{'''add_prefix_space''': True} if isinstance(lowerCamelCase_	,lowerCamelCase_) and not line.startswith(''' ''') else {}
				lowerCAmelCase__					:    Union[str, Any]												=					padding_side
				return tokenizer(
				    [line]	,max_length=lowerCamelCase_	,padding='''max_length''' if pad_to_max_length else None	,truncation=lowerCamelCase_	,return_tensors=lowerCamelCase_	,add_special_tokens=lowerCamelCase_	,**lowerCamelCase_	,)






def      lowerCAmelCase__		(   lowerCamelCase_		:		Optional[int]	,lowerCamelCase_		:		Dict	,lowerCamelCase_		:		Any=None	,):





				'''simple docstring'''

				lowerCAmelCase__					:    List[Any]												=					input_ids.ne(lowerCamelCase_).any(dim=0)
				if attention_mask is None:
								return input_ids[:, keep_column_mask]
				else:
								return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask])



class 	lowerCamelCase__      (							lowerCamelCase__):




		'''simple docstring'''



		def __init__(self		,__lowerCamelCase		,__lowerCamelCase		,__lowerCamelCase		,__lowerCamelCase		,__lowerCamelCase="train"		,__lowerCamelCase=None		,__lowerCamelCase=None		,__lowerCamelCase=None		,__lowerCamelCase=""		,)					->      List[str]:

						"""simple docstring"""






						super().__init__()
						lowerCAmelCase__					:    str												=					Path(__lowerCamelCase			).joinpath(type_path + '''.source'''			)
						lowerCAmelCase__					:    int												=					Path(__lowerCamelCase			).joinpath(type_path + '''.target'''			)
						lowerCAmelCase__					:    Tuple												=					self.get_char_lens(self.src_file			)
						lowerCAmelCase__					:    Dict												=					max_source_length
						lowerCAmelCase__					:    Optional[int]												=					max_target_length
						assert min(self.src_lens			) > 0, f"""found empty line in {self.src_file}"""
						lowerCAmelCase__					:    Tuple												=					tokenizer
						lowerCAmelCase__					:    List[Any]												=					prefix
						if n_obs is not None:
										lowerCAmelCase__					:    Optional[Any]												=					self.src_lens[:n_obs]
						lowerCAmelCase__					:    Any												=					src_lang
						lowerCAmelCase__					:    Optional[Any]												=					tgt_lang



		def __len__(self			)					->      str:

						"""simple docstring"""






						return len(self.src_lens			)



		def __getitem__(self		,__lowerCamelCase			)					->      Dict[str, torch.Tensor]:

						"""simple docstring"""






						lowerCAmelCase__					:    List[Any]												=					index + 1  # linecache starts at 1
						lowerCAmelCase__					:    Any												=					self.prefix + linecache.getline(str(self.src_file			)		,__lowerCamelCase			).rstrip('''\n'''			)
						lowerCAmelCase__					:    Any												=					linecache.getline(str(self.tgt_file			)		,__lowerCamelCase			).rstrip('''\n'''			)
						assert source_line, f"""empty source line for index {index}"""
						assert tgt_line, f"""empty tgt line for index {index}"""

						# Need to add eos token manually for T5
						if isinstance(self.tokenizer		,__lowerCamelCase			):
										source_line += self.tokenizer.eos_token
										tgt_line += self.tokenizer.eos_token

						# Pad source and target to the right
						lowerCAmelCase__					:    List[str]												=					(
						    self.tokenizer.question_encoder if isinstance(self.tokenizer		,__lowerCamelCase			) else self.tokenizer
						)
						lowerCAmelCase__					:    Dict												=					self.tokenizer.generator if isinstance(self.tokenizer		,__lowerCamelCase			) else self.tokenizer

						lowerCAmelCase__					:    Union[str, Any]												=					encode_line(__lowerCamelCase		,__lowerCamelCase		,self.max_source_length		,'''right'''			)
						lowerCAmelCase__					:    Any												=					encode_line(__lowerCamelCase		,__lowerCamelCase		,self.max_target_length		,'''right'''			)

						lowerCAmelCase__					:    List[str]												=					source_inputs['''input_ids'''].squeeze()
						lowerCAmelCase__					:    str												=					target_inputs['''input_ids'''].squeeze()
						lowerCAmelCase__					:    Tuple												=					source_inputs['''attention_mask'''].squeeze()
						return {
						    "input_ids": source_ids,
						    "attention_mask": src_mask,
						    "decoder_input_ids": target_ids,
						}



		@staticmethod
		def 		lowerCAmelCase__				(__lowerCamelCase			)					->      List[str]:

						"""simple docstring"""






						return [len(__lowerCamelCase			) for x in Path(__lowerCamelCase			).open().readlines()]



		def 		lowerCAmelCase__				(self		,__lowerCamelCase			)					->      Dict[str, torch.Tensor]:

						"""simple docstring"""






						lowerCAmelCase__					:    Union[str, Any]												=					torch.stack([x['''input_ids'''] for x in batch]			)
						lowerCAmelCase__					:    Union[str, Any]												=					torch.stack([x['''attention_mask'''] for x in batch]			)
						lowerCAmelCase__					:    List[Any]												=					torch.stack([x['''decoder_input_ids'''] for x in batch]			)
						lowerCAmelCase__					:    Any												=					(
						    self.tokenizer.generator.pad_token_id
						    if isinstance(self.tokenizer		,__lowerCamelCase			)
						    else self.tokenizer.pad_token_id
						)
						lowerCAmelCase__					:    Tuple												=					(
						    self.tokenizer.question_encoder.pad_token_id
						    if isinstance(self.tokenizer		,__lowerCamelCase			)
						    else self.tokenizer.pad_token_id
						)
						lowerCAmelCase__					:    Dict												=					trim_batch(__lowerCamelCase		,__lowerCamelCase			)
						lowerCAmelCase__						,		lowerCAmelCase__					:    Union[str, Any]												=					trim_batch(__lowerCamelCase		,__lowerCamelCase		,attention_mask=__lowerCamelCase			)
						lowerCAmelCase__					:    Union[str, Any]												=					{
						    '''input_ids''': source_ids,
						    '''attention_mask''': source_mask,
						    '''decoder_input_ids''': y,
						}
						return batch


__snake_case    :		Any  =getLogger(__name__)






def      lowerCAmelCase__		(   lowerCamelCase_		:		List[List]):





				'''simple docstring'''

				return list(itertools.chain.from_iterable(lowerCamelCase_))






def      lowerCAmelCase__		(   lowerCamelCase_		:		str):





				'''simple docstring'''

				lowerCAmelCase__					:    int												=					get_git_info()
				save_json(lowerCamelCase_	,os.path.join(lowerCamelCase_	,'''git_log.json'''))






def      lowerCAmelCase__		(   lowerCamelCase_		:		Tuple	,lowerCamelCase_		:		Union[str, Any]	,lowerCamelCase_		:		Tuple=4	,**lowerCamelCase_		:		List[str]):





				'''simple docstring'''

				with open(lowerCamelCase_	,'''w''') as f:
								json.dump(lowerCamelCase_	,lowerCamelCase_	,indent=lowerCamelCase_	,**lowerCamelCase_)






def      lowerCAmelCase__		(   lowerCamelCase_		:		Tuple):





				'''simple docstring'''

				with open(lowerCamelCase_) as f:
								return json.load(lowerCamelCase_)






def      lowerCAmelCase__		(   ):





				'''simple docstring'''

				lowerCAmelCase__					:    str												=					git.Repo(search_parent_directories=lowerCamelCase_)
				lowerCAmelCase__					:    List[Any]												=					{
				    '''repo_id''': str(lowerCamelCase_),
				    '''repo_sha''': str(repo.head.object.hexsha),
				    '''repo_branch''': str(repo.active_branch),
				    '''hostname''': str(socket.gethostname()),
				}
				return repo_infos






def      lowerCAmelCase__		(   lowerCamelCase_		:		Callable	,lowerCamelCase_		:		Iterable):





				'''simple docstring'''

				return list(map(lowerCamelCase_	,lowerCamelCase_))






def      lowerCAmelCase__		(   lowerCamelCase_		:		Any	,lowerCamelCase_		:		Optional[Any]):





				'''simple docstring'''

				with open(lowerCamelCase_	,'''wb''') as f:
								return pickle.dump(lowerCamelCase_	,lowerCamelCase_)






def      lowerCAmelCase__		(   lowerCamelCase_		:		int):





				'''simple docstring'''

				def remove_articles(lowerCamelCase_		:		List[str]):
								return re.sub(r'''\b(a|an|the)\b'''	,''' '''	,lowerCamelCase_)

				def white_space_fix(lowerCamelCase_		:		Optional[int]):
								return " ".join(text.split())

				def remove_punc(lowerCamelCase_		:		List[str]):
								lowerCAmelCase__					:    List[Any]												=					set(string.punctuation)
								return "".join(ch for ch in text if ch not in exclude)

				def lower(lowerCamelCase_		:		Optional[int]):
								return text.lower()

				return white_space_fix(remove_articles(remove_punc(lower(lowerCamelCase_))))






def      lowerCAmelCase__		(   lowerCamelCase_		:		List[Any]	,lowerCamelCase_		:		Optional[int]):





				'''simple docstring'''

				lowerCAmelCase__					:    Optional[Any]												=					normalize_answer(lowerCamelCase_).split()
				lowerCAmelCase__					:    str												=					normalize_answer(lowerCamelCase_).split()
				lowerCAmelCase__					:    str												=					Counter(lowerCamelCase_) & Counter(lowerCamelCase_)
				lowerCAmelCase__					:    Dict												=					sum(common.values())
				if num_same == 0:
								return 0
				lowerCAmelCase__					:    Optional[int]												=					1.0 * num_same / len(lowerCamelCase_)
				lowerCAmelCase__					:    Optional[Any]												=					1.0 * num_same / len(lowerCamelCase_)
				lowerCAmelCase__					:    Optional[Any]												=					(2 * precision * recall) / (precision + recall)
				return fa






def      lowerCAmelCase__		(   lowerCamelCase_		:		Union[str, Any]	,lowerCamelCase_		:		Any):





				'''simple docstring'''

				return normalize_answer(lowerCamelCase_) == normalize_answer(lowerCamelCase_)






def      lowerCAmelCase__		(   lowerCamelCase_		:		List[str]	,lowerCamelCase_		:		List[str]):





				'''simple docstring'''

				assert len(lowerCamelCase_) == len(lowerCamelCase_)
				lowerCAmelCase__					:    List[str]												=					0
				for hypo, pred in zip(lowerCamelCase_	,lowerCamelCase_):
								em += exact_match_score(lowerCamelCase_	,lowerCamelCase_)
				if len(lowerCamelCase_) > 0:
								em /= len(lowerCamelCase_)
				return {"em": em}






def      lowerCAmelCase__		(   lowerCamelCase_		:		int):





				'''simple docstring'''

				return model_prefix.startswith('''rag''')






def      lowerCAmelCase__		(   lowerCamelCase_		:		List[str]	,lowerCamelCase_		:		Dict	,lowerCamelCase_		:		str):





				'''simple docstring'''

				lowerCAmelCase__					:    Any												=					{p: p for p in extra_params}
				# T5 models don't have `dropout` param, they have `dropout_rate` instead
				lowerCAmelCase__					:    Optional[int]												=					'''dropout_rate'''
				for p in extra_params:
								if getattr(lowerCamelCase_	,lowerCamelCase_	,lowerCamelCase_):
												if not hasattr(lowerCamelCase_	,lowerCamelCase_) and not hasattr(lowerCamelCase_	,equivalent_param[p]):
																logger.info('''config doesn\'t have a `{}` attribute'''.format(lowerCamelCase_))
																delattr(lowerCamelCase_	,lowerCamelCase_)
																continue
												lowerCAmelCase__					:    Dict												=					p if hasattr(lowerCamelCase_	,lowerCamelCase_) else equivalent_param[p]
												setattr(lowerCamelCase_	,lowerCamelCase_	,getattr(lowerCamelCase_	,lowerCamelCase_))
												delattr(lowerCamelCase_	,lowerCamelCase_)
				return hparams, config

