"""simple docstring"""






import shutil
import tempfile
import unittest

import pytest

from transformers import WhisperTokenizer, is_speech_available
from transformers.testing_utils import require_sentencepiece, require_torch, require_torchaudio

from .test_feature_extraction_whisper import floats_list


if is_speech_available():
						from transformers import WhisperFeatureExtractor, WhisperProcessor


lowerCAmelCase__  :  Union[str, Any]											=     50_358
lowerCAmelCase__  :  Optional[int]											=     50_362
@require_torch
@require_torchaudio
@require_sentencepiece
class     snake_case	(			unittest.TestCase    ):




					"""simple docstring"""

					def 		__lowerCAmelCase						(    self       :     List[Any]      ):
									UpperCAmelCase__					=							'openai/whisper-small.en'
									UpperCAmelCase__					=							tempfile.mkdtemp()







					def 		__lowerCAmelCase						(    self       :     Optional[Any]   ,**lowerCamelCase__       :     List[Any]      ):
									return WhisperTokenizer.from_pretrained(self.checkpoint   ,**lowerCamelCase__      )







					def 		__lowerCAmelCase						(    self       :     Dict   ,**lowerCamelCase__       :     List[Any]      ):
									return WhisperFeatureExtractor.from_pretrained(self.checkpoint   ,**lowerCamelCase__      )







					def 		__lowerCAmelCase						(    self       :     Optional[int]      ):
									shutil.rmtree(self.tmpdirname      )







					def 		__lowerCAmelCase						(    self       :     str      ):
									UpperCAmelCase__					=							self.get_tokenizer()
									UpperCAmelCase__					=							self.get_feature_extractor()

									UpperCAmelCase__					=							WhisperProcessor(tokenizer=lowerCamelCase__   ,feature_extractor=lowerCamelCase__      )

									processor.save_pretrained(self.tmpdirname      )
									UpperCAmelCase__					=							WhisperProcessor.from_pretrained(self.tmpdirname      )

									self.assertEqual(processor.tokenizer.get_vocab()   ,tokenizer.get_vocab()      )
									self.assertIsInstance(processor.tokenizer   ,lowerCamelCase__      )

									self.assertEqual(processor.feature_extractor.to_json_string()   ,feature_extractor.to_json_string()      )
									self.assertIsInstance(processor.feature_extractor   ,lowerCamelCase__      )







					def 		__lowerCAmelCase						(    self       :     Union[str, Any]      ):
									UpperCAmelCase__					=							WhisperProcessor(tokenizer=self.get_tokenizer()   ,feature_extractor=self.get_feature_extractor()      )
									processor.save_pretrained(self.tmpdirname      )

									UpperCAmelCase__					=							self.get_tokenizer(bos_token='(BOS)'   ,eos_token='(EOS)'      )
									UpperCAmelCase__					=							self.get_feature_extractor(do_normalize=lowerCamelCase__   ,padding_value=1.0      )

									UpperCAmelCase__					=							WhisperProcessor.from_pretrained(
									    self.tmpdirname   ,bos_token='(BOS)'   ,eos_token='(EOS)'   ,do_normalize=lowerCamelCase__   ,padding_value=1.0      )

									self.assertEqual(processor.tokenizer.get_vocab()   ,tokenizer_add_kwargs.get_vocab()      )
									self.assertIsInstance(processor.tokenizer   ,lowerCamelCase__      )

									self.assertEqual(processor.feature_extractor.to_json_string()   ,feature_extractor_add_kwargs.to_json_string()      )
									self.assertIsInstance(processor.feature_extractor   ,lowerCamelCase__      )







					def 		__lowerCAmelCase						(    self       :     Optional[int]      ):
									UpperCAmelCase__					=							self.get_feature_extractor()
									UpperCAmelCase__					=							self.get_tokenizer()

									UpperCAmelCase__					=							WhisperProcessor(tokenizer=lowerCamelCase__   ,feature_extractor=lowerCamelCase__      )

									UpperCAmelCase__					=							floats_list((3, 1_000)      )

									UpperCAmelCase__					=							feature_extractor(lowerCamelCase__   ,return_tensors='np'      )
									UpperCAmelCase__					=							processor(lowerCamelCase__   ,return_tensors='np'      )

									for key in input_feat_extract.keys():
													self.assertAlmostEqual(input_feat_extract[key].sum()   ,input_processor[key].sum()   ,delta=1e-2      )







					def 		__lowerCAmelCase						(    self       :     List[Any]      ):
									UpperCAmelCase__					=							self.get_feature_extractor()
									UpperCAmelCase__					=							self.get_tokenizer()

									UpperCAmelCase__					=							WhisperProcessor(tokenizer=lowerCamelCase__   ,feature_extractor=lowerCamelCase__      )

									UpperCAmelCase__					=							'This is a test string'

									UpperCAmelCase__					=							processor(text=lowerCamelCase__      )

									UpperCAmelCase__					=							tokenizer(lowerCamelCase__      )

									for key in encoded_tok.keys():
													self.assertListEqual(encoded_tok[key]   ,encoded_processor[key]      )







					def 		__lowerCAmelCase						(    self       :     List[Any]      ):
									UpperCAmelCase__					=							self.get_feature_extractor()
									UpperCAmelCase__					=							self.get_tokenizer()

									UpperCAmelCase__					=							WhisperProcessor(tokenizer=lowerCamelCase__   ,feature_extractor=lowerCamelCase__      )

									UpperCAmelCase__					=							[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

									UpperCAmelCase__					=							processor.batch_decode(lowerCamelCase__      )
									UpperCAmelCase__					=							tokenizer.batch_decode(lowerCamelCase__      )

									self.assertListEqual(lowerCamelCase__   ,lowerCamelCase__      )







					def 		__lowerCAmelCase						(    self       :     Optional[int]      ):
									UpperCAmelCase__					=							self.get_feature_extractor()
									UpperCAmelCase__					=							self.get_tokenizer()

									UpperCAmelCase__					=							WhisperProcessor(tokenizer=lowerCamelCase__   ,feature_extractor=lowerCamelCase__      )

									self.assertListEqual(
									    processor.model_input_names   ,feature_extractor.model_input_names   ,msg='`processor` and `feature_extractor` model input names do not match'   ,)







					def 		__lowerCAmelCase						(    self       :     Union[str, Any]      ):
									UpperCAmelCase__					=							self.get_feature_extractor()
									UpperCAmelCase__					=							self.get_tokenizer()

									UpperCAmelCase__					=							WhisperProcessor(tokenizer=lowerCamelCase__   ,feature_extractor=lowerCamelCase__      )
									UpperCAmelCase__					=							processor.get_decoder_prompt_ids(task='transcribe'   ,no_timestamps=lowerCamelCase__      )

									self.assertIsInstance(lowerCamelCase__   ,lowerCamelCase__      )
									for ids in forced_decoder_ids:
													self.assertIsInstance(lowerCamelCase__   ,(list, tuple)      )

									UpperCAmelCase__					=							[TRANSCRIBE, NOTIMESTAMPS]
									self.assertListEqual([ids[-1] for ids in forced_decoder_ids]   ,lowerCamelCase__      )







					def 		__lowerCAmelCase						(    self       :     str      ):
									UpperCAmelCase__					=							WhisperProcessor(tokenizer=self.get_tokenizer()   ,feature_extractor=self.get_feature_extractor()      )
									UpperCAmelCase__					=							processor.get_prompt_ids('Mr. Quilter'      )
									UpperCAmelCase__					=							processor.tokenizer.decode(lowerCamelCase__      )

									self.assertListEqual(prompt_ids.tolist()   ,[50_360, 1_770, 13, 2_264, 346, 353]      )
									self.assertEqual(lowerCamelCase__   ,'<|startofprev|> Mr. Quilter'      )







					def 		__lowerCAmelCase						(    self       :     int      ):
									UpperCAmelCase__					=							WhisperProcessor(tokenizer=self.get_tokenizer()   ,feature_extractor=self.get_feature_extractor()      )
									UpperCAmelCase__					=							processor.get_prompt_ids(''      )
									UpperCAmelCase__					=							processor.tokenizer.decode(lowerCamelCase__      )

									self.assertListEqual(prompt_ids.tolist()   ,[50_360, 220]      )
									self.assertEqual(lowerCamelCase__   ,'<|startofprev|> '      )







					def 		__lowerCAmelCase						(    self       :     Dict      ):
									UpperCAmelCase__					=							WhisperProcessor(tokenizer=self.get_tokenizer()   ,feature_extractor=self.get_feature_extractor()      )

									def _test_prompt_error_raised_helper(lowerCamelCase__       :     Optional[int]   ,lowerCamelCase__       :     List[str]      ):
													with pytest.raises(lowerCamelCase__      ) as excinfo:
																	processor.get_prompt_ids(lowerCamelCase__      )
													UpperCAmelCase__					=							f'''Encountered text in the prompt corresponding to disallowed special token: {special_token}.'''
													self.assertEqual(lowerCamelCase__   ,str(excinfo.value      )      )

									_test_prompt_error_raised_helper('<|startofprev|> test'   ,'<|startofprev|>'      )
									_test_prompt_error_raised_helper('test <|notimestamps|>'   ,'<|notimestamps|>'      )
									_test_prompt_error_raised_helper('test <|zh|> test <|transcribe|>'   ,'<|zh|>'      )




"""simple docstring"""






import collections

from .utils import ExplicitEnum, is_torch_available, logging


if is_torch_available():
						import torch


lowerCAmelCase__  :  Optional[Any]											=     logging.get_logger(__name__)
class     snake_case	:




					"""simple docstring"""

					def __init__(    self       :     Optional[Any]   ,lowerCamelCase__       :     Dict   ,lowerCamelCase__       :     Optional[Any]=21   ,lowerCamelCase__       :     str=[]   ,lowerCamelCase__       :     Any=None      ):
									UpperCAmelCase__					=							model
									UpperCAmelCase__					=							trace_batch_nums
									UpperCAmelCase__					=							abort_after_batch_num

									# keep a LIFO buffer of frames to dump as soon as inf/nan is encountered to give context to the problem emergence
									UpperCAmelCase__					=							collections.deque([]   ,lowerCamelCase__      )
									UpperCAmelCase__					=							[]
									UpperCAmelCase__					=							0
									UpperCAmelCase__					=							0
									UpperCAmelCase__					=							False
									UpperCAmelCase__					=							'                 '

									self.analyse_model()

									self.register_forward_hook()







					def 		__lowerCAmelCase						(    self       :     Union[str, Any]   ,lowerCamelCase__       :     Tuple=None      ):
									if frame is not None:
													self.expand_frame(lowerCamelCase__      )
									self.frames.append('\n'.join(self.frame      )      )
									UpperCAmelCase__					=							[]  # start a new frame







					def 		__lowerCAmelCase						(    self       :     int   ,lowerCamelCase__       :     int      ):
									self.frame.append(lowerCamelCase__      )







					def 		__lowerCAmelCase						(    self       :     List[str]      ):
									print('\n'.join(self.frames      )      )
									UpperCAmelCase__					=							[]







					def 		__lowerCAmelCase						(    self       :     Tuple      ):
									UpperCAmelCase__					=							[]







					def 		__lowerCAmelCase						(    self       :     Dict      ):
									print(f'''\nDetected inf/nan during batch_number={self.batch_number}'''      )
									print(f'''Last {len(self.frames      )} forward frames:'''      )
									print(f'''{"abs min":8} {"abs max":8} metadata'''      )
									print('\n'.join(self.frames      )      )
									print('\n\n'      )
									UpperCAmelCase__					=							[]







					def 		__lowerCAmelCase						(    self       :     Tuple      ):
									# extract the fully qualified module names, to be able to report at run time. e.g.:
									# encoder.block.2.layer.0.SelfAttention.o
									#
									# for shared weights only the first shared module name will be registered
									UpperCAmelCase__					=							{m: name for name, m in self.model.named_modules()}
									# self.longest_module_name = max(len(v) for v in self.module_names.values())







					def 		__lowerCAmelCase						(    self       :     Optional[Any]   ,lowerCamelCase__       :     int   ,lowerCamelCase__       :     List[Any]      ):
									if torch.is_tensor(lowerCamelCase__      ):
													self.expand_frame(get_abs_min_max(lowerCamelCase__   ,lowerCamelCase__      )      )
													if detect_overflow(lowerCamelCase__   ,lowerCamelCase__      ):
																	UpperCAmelCase__					=							True
									elif var is None:
													self.expand_frame(f'''{"None":>17} {ctx}'''      )
									else:
													self.expand_frame(f'''{"not a tensor":>17} {ctx}'''      )







					def 		__lowerCAmelCase						(    self       :     Optional[int]      ):
									self.expand_frame(f'''\n\n{self.prefix} *** Starting batch number={self.batch_number} ***'''      )
									self.expand_frame(f'''{"abs min":8} {"abs max":8} metadata'''      )







					def 		__lowerCAmelCase						(    self       :     Optional[int]      ):
									self.expand_frame(f'''{self.prefix} *** Finished batch number={self.batch_number-1} ***\n\n'''      )







					def 		__lowerCAmelCase						(    self       :     List[str]   ,lowerCamelCase__       :     List[str]   ,lowerCamelCase__       :     List[Any]   ,lowerCamelCase__       :     Optional[Any]      ):
									self.expand_frame(f'''{self.prefix} {self.module_names[module]} {module.__class__.__name__}'''      )

									# params
									for name, p in module.named_parameters(recurse=lowerCamelCase__      ):
													self.analyse_variable(lowerCamelCase__   ,lowerCamelCase__      )

									# inputs
									if isinstance(lowerCamelCase__   ,lowerCamelCase__      ):
													for i, x in enumerate(lowerCamelCase__      ):
																	self.analyse_variable(lowerCamelCase__   ,f'''input[{i}]'''      )
									else:
													self.analyse_variable(lowerCamelCase__   ,'input'      )

									# outputs
									if isinstance(lowerCamelCase__   ,lowerCamelCase__      ):
													for i, x in enumerate(lowerCamelCase__      ):
																	# possibly a tuple of tuples
																	if isinstance(lowerCamelCase__   ,lowerCamelCase__      ):
																					for j, y in enumerate(lowerCamelCase__      ):
																									self.analyse_variable(lowerCamelCase__   ,f'''output[{i}][{j}]'''      )
																	else:
																					self.analyse_variable(lowerCamelCase__   ,f'''output[{i}]'''      )
									else:
													self.analyse_variable(lowerCamelCase__   ,'output'      )

									self.save_frame()







					def 		__lowerCAmelCase						(    self       :     Union[str, Any]      ):
									self.model.apply(self._register_forward_hook      )







					def 		__lowerCAmelCase						(    self       :     List[Any]   ,lowerCamelCase__       :     str      ):
									module.register_forward_hook(self.forward_hook      )







					def 		__lowerCAmelCase						(    self       :     Optional[Any]   ,lowerCamelCase__       :     Any   ,lowerCamelCase__       :     str   ,lowerCamelCase__       :     Union[str, Any]      ):
									# - input is a tuple of packed inputs (could be non-Tensors)
									# - output could be a Tensor or a tuple of Tensors and non-Tensors

									UpperCAmelCase__					=							False

									UpperCAmelCase__					=							True if self.batch_number in self.trace_batch_nums else False
									if trace_mode:
													self.reset_saved_frames()

									if self.total_calls == 0:
													self.batch_start_frame()
									self.total_calls += 1

									# count batch numbers - the very first forward hook of the batch will be called when the
									# batch completes - i.e. it gets called very last - we know this batch has finished
									if module == self.model:
													self.batch_number += 1
													UpperCAmelCase__					=							True

									self.create_frame(lowerCamelCase__   ,lowerCamelCase__   ,lowerCamelCase__      )

									# if last_frame_of_batch:
									#     self.batch_end_frame()

									if trace_mode:
													self.trace_frames()

									if last_frame_of_batch:
													self.batch_start_frame()

									if self.detected_overflow and not trace_mode:
													self.dump_saved_frames()

													# now we can abort, as it's pointless to continue running
													raise ValueError(
													    'DebugUnderflowOverflow: inf/nan detected, aborting as there is no point running further. '
													    'Please scroll up above this traceback to see the activation values prior to this event.'      )

									# abort after certain batch if requested to do so
									if self.abort_after_batch_num is not None and self.batch_number > self.abort_after_batch_num:
													raise ValueError(
													    f'''DebugUnderflowOverflow: aborting after {self.batch_number} batches due to'''
													    f''' `abort_after_batch_num={self.abort_after_batch_num}` arg'''      )






def   a_						( lowerCamelCase ,      lowerCamelCase	):
				UpperCAmelCase__					=							var.abs()
				return f'''{abs_var.min():8.2e} {abs_var.max():8.2e} {ctx}'''



def   a_						( lowerCamelCase ,      lowerCamelCase	):
				UpperCAmelCase__					=							False
				if torch.isnan(lowerCamelCase	).any().item():
								UpperCAmelCase__					=							True
								print(f'''{ctx} has nans'''	)
				if torch.isinf(lowerCamelCase	).any().item():
								UpperCAmelCase__					=							True
								print(f'''{ctx} has infs'''	)

				# if needed to monitor large elements can enable the following
				if 0:  # and detected:
								UpperCAmelCase__					=							var[torch.ge(var.abs() ,      1_0_0	)]
								if naaa.numel() > 0:
												print(f'''{ctx}:  n100={naaa.numel()}'''	)
								UpperCAmelCase__					=							var[torch.ge(var.abs() ,      1_0_0_0	)]
								if naaaa.numel() > 0:
												print(f'''{ctx}: n1000={naaaa.numel()}'''	)
								UpperCAmelCase__					=							var[torch.ge(var.abs() ,      1_0_0_0_0	)]
								if naaaaa.numel() > 0:
												print(f'''{ctx}: n10000={naaaaa.numel()}'''	)

				if 0:
								print(f'''min={var.min():9.2e} max={var.max():9.2e}'''	)

				if 0:
								print(f'''min={var.min():9.2e} max={var.max():9.2e} var={var.var():9.2e} mean={var.mean():9.2e} ({ctx})'''	)

				return detected







class     snake_case	(			__UpperCAmelCase    ):




					"""simple docstring"""

					snake_case__       =			"underflow_overflow"
					snake_case__       =			"tpu_metrics_debug"



