






"""simple docstring"""


import os
import unittest

from transformers import BatchEncoding
from transformers.models.bert.tokenization_bert import (
    BasicTokenizer,
    WordpieceTokenizer,
    _is_control,
    _is_punctuation,
    _is_whitespace,
)
from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer
from transformers.testing_utils import require_torch, slow

from ...test_tokenization_common import TokenizerTesterMixin


class 					snake_case		(							_lowerCAmelCase   ,	unittest.TestCase						):


   '''simple docstring'''

   A_						:	int						 = ProphetNetTokenizer
   A_						:	Tuple						 = False


   def 				_SCREAMING_SNAKE_CASE				(	self :     Optional[Any]  ):

     '''simple docstring'''
     super().setUp()

     __A									= [
         '''[UNK]''',
         '''[CLS]''',
         '''[SEP]''',
         '''[PAD]''',
         '''[MASK]''',
         '''want''',
         '''##want''',
         '''##ed''',
         '''wa''',
         '''un''',
         '''runn''',
         '''##ing''',
         ''',''',
         '''low''',
         '''lowest''',
     ]
     __A									= os.path.join(self.tmpdirname,       VOCAB_FILES_NAMES['''vocab_file''']  )
     with open(self.vocab_file,       '''w''',       encoding='''utf-8'''  ) as vocab_writer:
       vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens]  )  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     str,       _lowerCamelCase :     Optional[Any]  ):

     '''simple docstring'''
     __A									= '''UNwant\u00E9d,running'''
     __A									= '''unwanted, running'''
     return input_text, output_text


   def 				_SCREAMING_SNAKE_CASE				(	self :     str  ):

     '''simple docstring'''
     __A									= self.tokenizer_class(self.vocab_file  )

     __A									= tokenizer.tokenize('''UNwant\u00E9d,running'''  )
     self.assertListEqual(_lowerCamelCase,       ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing''']  )
     self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCamelCase  ),       [9, 6, 7, 12, 10, 11]  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     Optional[int]  ):

     '''simple docstring'''
     __A									= BasicTokenizer()

     self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz'''  ),       ['''ah''', '''\u535A''', '''\u63A8''', '''zz''']  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     str  ):

     '''simple docstring'''
     __A									= BasicTokenizer(do_lower_case=_lowerCamelCase  )

     self.assertListEqual(
         tokenizer.tokenize(''' \tHeLLo!how  \n Are yoU?  '''  ),       ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?''']  )
     self.assertListEqual(tokenizer.tokenize('''H\u00E9llo'''  ),       ['''hello''']  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     Optional[Any]  ):

     '''simple docstring'''
     __A									= BasicTokenizer(do_lower_case=_lowerCamelCase,       strip_accents=_lowerCamelCase  )

     self.assertListEqual(
         tokenizer.tokenize(''' \tHäLLo!how  \n Are yoU?  '''  ),       ['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?''']  )
     self.assertListEqual(tokenizer.tokenize('''H\u00E9llo'''  ),       ['''h\u00E9llo''']  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     str  ):

     '''simple docstring'''
     __A									= BasicTokenizer(do_lower_case=_lowerCamelCase,       strip_accents=_lowerCamelCase  )

     self.assertListEqual(
         tokenizer.tokenize(''' \tHäLLo!how  \n Are yoU?  '''  ),       ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?''']  )
     self.assertListEqual(tokenizer.tokenize('''H\u00E9llo'''  ),       ['''hello''']  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     Dict  ):

     '''simple docstring'''
     __A									= BasicTokenizer(do_lower_case=_lowerCamelCase  )

     self.assertListEqual(
         tokenizer.tokenize(''' \tHäLLo!how  \n Are yoU?  '''  ),       ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?''']  )
     self.assertListEqual(tokenizer.tokenize('''H\u00E9llo'''  ),       ['''hello''']  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     str  ):

     '''simple docstring'''
     __A									= BasicTokenizer(do_lower_case=_lowerCamelCase  )

     self.assertListEqual(
         tokenizer.tokenize(''' \tHeLLo!how  \n Are yoU?  '''  ),       ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''']  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     Tuple  ):

     '''simple docstring'''
     __A									= BasicTokenizer(do_lower_case=_lowerCamelCase,       strip_accents=_lowerCamelCase  )

     self.assertListEqual(
         tokenizer.tokenize(''' \tHäLLo!how  \n Are yoU?  '''  ),       ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''']  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     Union[str, Any]  ):

     '''simple docstring'''
     __A									= BasicTokenizer(do_lower_case=_lowerCamelCase,       strip_accents=_lowerCamelCase  )

     self.assertListEqual(
         tokenizer.tokenize(''' \tHäLLo!how  \n Are yoU?  '''  ),       ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''']  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     List[str]  ):

     '''simple docstring'''
     __A									= BasicTokenizer(do_lower_case=_lowerCamelCase,       never_split=['''[UNK]''']  )

     self.assertListEqual(
         tokenizer.tokenize(''' \tHeLLo!how  \n Are yoU? [UNK]'''  ),       ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]''']  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     Any  ):

     '''simple docstring'''
     __A									= ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''']

     __A									= {}
     for i, token in enumerate(_lowerCamelCase  ):
       __A									= i
     __A									= WordpieceTokenizer(vocab=_lowerCamelCase,       unk_token='''[UNK]'''  )

     self.assertListEqual(tokenizer.tokenize(''''''  ),       []  )

     self.assertListEqual(tokenizer.tokenize('''unwanted running'''  ),       ['''un''', '''##want''', '''##ed''', '''runn''', '''##ing''']  )

     self.assertListEqual(tokenizer.tokenize('''unwantedX running'''  ),       ['''[UNK]''', '''runn''', '''##ing''']  )


   @require_torch
   def 				_SCREAMING_SNAKE_CASE				(	self :     Dict  ):

     '''simple docstring'''
     __A									= self.tokenizer_class.from_pretrained('''microsoft/prophetnet-large-uncased'''  )

     __A									= ['''A long paragraph for summarization.''', '''Another paragraph for summarization.''']
     __A									= [10_37, 21_46, 2_04_23, 20_05, 76_80, 78_49, 39_89, 10_12, 1_02]
     __A									= tokenizer(_lowerCamelCase,       padding=_lowerCamelCase,       return_tensors='''pt'''  )
     self.assertIsInstance(_lowerCamelCase,       _lowerCamelCase  )
     __A									= list(batch.input_ids.numpy()[0]  )
     self.assertListEqual(_lowerCamelCase,       _lowerCamelCase  )

     self.assertEqual((2, 9),       batch.input_ids.shape  )
     self.assertEqual((2, 9),       batch.attention_mask.shape  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     List[str]  ):

     '''simple docstring'''
     self.assertTrue(_is_whitespace(''' '''  )  )
     self.assertTrue(_is_whitespace('''\t'''  )  )
     self.assertTrue(_is_whitespace('''\r'''  )  )
     self.assertTrue(_is_whitespace('''\n'''  )  )
     self.assertTrue(_is_whitespace('''\u00A0'''  )  )

     self.assertFalse(_is_whitespace('''A'''  )  )
     self.assertFalse(_is_whitespace('''-'''  )  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     Union[str, Any]  ):

     '''simple docstring'''
     self.assertTrue(_is_control('''\u0005'''  )  )

     self.assertFalse(_is_control('''A'''  )  )
     self.assertFalse(_is_control(''' '''  )  )
     self.assertFalse(_is_control('''\t'''  )  )
     self.assertFalse(_is_control('''\r'''  )  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     int  ):

     '''simple docstring'''
     self.assertTrue(_is_punctuation('''-'''  )  )
     self.assertTrue(_is_punctuation('''$'''  )  )
     self.assertTrue(_is_punctuation('''`'''  )  )
     self.assertTrue(_is_punctuation('''.'''  )  )

     self.assertFalse(_is_punctuation('''A'''  )  )
     self.assertFalse(_is_punctuation(''' '''  )  )






   @slow
   def 				_SCREAMING_SNAKE_CASE				(	self :     Union[str, Any]  ):

     '''simple docstring'''
     __A									= self.tokenizer_class.from_pretrained('''microsoft/prophetnet-large-uncased'''  )

     __A									= tokenizer.encode('''sequence builders''',       add_special_tokens=_lowerCamelCase  )
     __A									= tokenizer.encode('''multi-sequence build''',       add_special_tokens=_lowerCamelCase  )

     __A									= tokenizer.build_inputs_with_special_tokens(_lowerCamelCase  )
     __A									= tokenizer.build_inputs_with_special_tokens(_lowerCamelCase,       _lowerCamelCase  )

     assert encoded_sentence == text + [1_02]
     assert encoded_pair == text + [1_02] + text_a + [1_02]












"""simple docstring"""


import itertools
import random
import unittest

import numpy as np

from transformers import ASTFeatureExtractor
from transformers.testing_utils import require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


lowercase_				     =     random.Random()

if is_torch_available():
       import torch



def 					lowerCAmelCase				(    __UpperCamelCase		,       __UpperCamelCase=1.0		,       __UpperCamelCase=None		,       __UpperCamelCase=None ):




  """simple docstring"""







  if rng is None:
    __A									= global_rng

  __A									= []
  for batch_idx in range(shape[0] ):
    values.append([] )
    for _ in range(shape[1] ):
      values[-1].append(rng.random() * scale )

  return values


class 					snake_case		(							unittest.TestCase						):


   '''simple docstring'''

   def __init__(	self :     Any,       _lowerCamelCase :     List[str],       _lowerCamelCase :     Any=7,       _lowerCamelCase :     Optional[int]=4_00,       _lowerCamelCase :     Optional[int]=20_00,       _lowerCamelCase :     Dict=1,       _lowerCamelCase :     Optional[Any]=0.0,       _lowerCamelCase :     int=1_60_00,       _lowerCamelCase :     Optional[int]=True,       _lowerCamelCase :     Dict=True,       ):

     '''simple docstring'''
     __A									= parent
     __A									= batch_size
     __A									= min_seq_length
     __A									= max_seq_length
     __A									= (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
     __A									= feature_size
     __A									= padding_value
     __A									= sampling_rate
     __A									= return_attention_mask
     __A									= do_normalize


   def 				_SCREAMING_SNAKE_CASE				(	self :     Union[str, Any]  ):

     '''simple docstring'''
     return {
         "feature_size": self.feature_size,
         "padding_value": self.padding_value,
         "sampling_rate": self.sampling_rate,
         "return_attention_mask": self.return_attention_mask,
         "do_normalize": self.do_normalize,
     }






   def 				_SCREAMING_SNAKE_CASE				(	self :     Any,       _lowerCamelCase :     Optional[Any]=False,       _lowerCamelCase :     int=False  ):

     '''simple docstring'''
     def _flatten(_lowerCamelCase :     List[str]  ):
       return list(itertools.chain(*_lowerCamelCase  )  )

     if equal_length:
       __A									= floats_list((self.batch_size, self.max_seq_length)  )
     else:
       # make sure that inputs increase in size
       __A									= [
           _flatten(floats_list((x, self.feature_size)  )  )
           for x in range(self.min_seq_length,       self.max_seq_length,       self.seq_length_diff  )
       ]

     if numpify:
       __A									= [np.asarray(_lowerCamelCase  ) for x in speech_inputs]

     return speech_inputs





@require_torch
@require_torchaudio
class 					snake_case		(							_lowerCAmelCase   ,	unittest.TestCase						):


   '''simple docstring'''

   A_						:	int						 = ASTFeatureExtractor


   def 				_SCREAMING_SNAKE_CASE				(	self :     Tuple  ):

     '''simple docstring'''
     __A									= ASTFeatureExtractionTester(self  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     Dict  ):

     '''simple docstring'''
     # Tests that all call wrap to encode_plus and batch_encode_plus
     __A									= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()  )
     # create three inputs of length 800, 1000, and 1200
     __A									= [floats_list((1, x)  )[0] for x in range(8_00,       14_00,       2_00  )]
     __A									= [np.asarray(_lowerCamelCase  ) for speech_input in speech_inputs]

     # Test not batched input
     __A									= feat_extract(speech_inputs[0],       return_tensors='''np'''  ).input_values
     __A									= feat_extract(np_speech_inputs[0],       return_tensors='''np'''  ).input_values
     self.assertTrue(np.allclose(_lowerCamelCase,       _lowerCamelCase,       atol=1e-3  )  )

     # Test batched
     __A									= feat_extract(_lowerCamelCase,       padding=_lowerCamelCase,       return_tensors='''np'''  ).input_values
     __A									= feat_extract(_lowerCamelCase,       padding=_lowerCamelCase,       return_tensors='''np'''  ).input_values
     for enc_seq_a, enc_seq_a in zip(_lowerCamelCase,       _lowerCamelCase  ):
       self.assertTrue(np.allclose(_lowerCamelCase,       _lowerCamelCase,       atol=1e-3  )  )

     # Test 2-D numpy arrays are batched.
     __A									= [floats_list((1, x)  )[0] for x in (8_00, 8_00, 8_00)]
     __A									= np.asarray(_lowerCamelCase  )
     __A									= feat_extract(_lowerCamelCase,       return_tensors='''np'''  ).input_values
     __A									= feat_extract(_lowerCamelCase,       return_tensors='''np'''  ).input_values
     for enc_seq_a, enc_seq_a in zip(_lowerCamelCase,       _lowerCamelCase  ):
       self.assertTrue(np.allclose(_lowerCamelCase,       _lowerCamelCase,       atol=1e-3  )  )


   @require_torch
   def 				_SCREAMING_SNAKE_CASE				(	self :     Union[str, Any]  ):

     '''simple docstring'''
     import torch

     __A									= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()  )
     __A									= np.random.rand(1_00  ).astype(np.floataa  )
     __A									= np_speech_inputs.tolist()

     for inputs in [py_speech_inputs, np_speech_inputs]:
       __A									= feature_extractor.pad([{'''input_values''': inputs}],       return_tensors='''np'''  )
       self.assertTrue(np_processed.input_values.dtype == np.floataa  )
       __A									= feature_extractor.pad([{'''input_values''': inputs}],       return_tensors='''pt'''  )
       self.assertTrue(pt_processed.input_values.dtype == torch.floataa  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     Optional[int],       _lowerCamelCase :     Union[str, Any]  ):

     '''simple docstring'''
     from datasets import load_dataset

     __A									= load_dataset('''hf-internal-testing/librispeech_asr_dummy''',       '''clean''',       split='''validation'''  )
     # automatic decoding with librispeech
     __A									= ds.sort('''id'''  ).select(range(_lowerCamelCase  )  )[:num_samples]['''audio''']

     return [x["array"] for x in speech_samples]






   @require_torch
   def 				_SCREAMING_SNAKE_CASE				(	self :     Optional[Any]  ):

     '''simple docstring'''
     # fmt: off
     __A									= torch.tensor(
         [-0.98_94, -1.27_76, -0.90_66, -1.27_76, -0.93_49, -1.26_09, -1.03_86, -1.27_76,
          -1.15_61, -1.27_76, -1.20_52, -1.27_23, -1.21_90, -1.21_32, -1.27_76, -1.11_33,
          -1.19_53, -1.13_43, -1.15_84, -1.22_03, -1.17_70, -1.24_74, -1.23_81, -1.19_36,
          -0.92_70, -0.83_17, -0.80_49, -0.77_06, -0.75_65, -0.78_69]  )
     # fmt: on

     __A									= self._load_datasamples(1  )
     __A									= ASTFeatureExtractor()
     __A									= feature_extractor(_lowerCamelCase,       return_tensors='''pt'''  ).input_values
     self.assertEquals(input_values.shape,       (1, 10_24, 1_28)  )
     self.assertTrue(torch.allclose(input_values[0, 0, :30],       _lowerCamelCase,       atol=1e-4  )  )




