




import random
import shutil
import tempfile
import unittest

import numpy as np

from transformers import TaTokenizer, TaTokenizerFast
from transformers.testing_utils import require_sentencepiece, require_torch
from transformers.utils.import_utils import is_speech_available, is_torch_available


if is_torch_available():
 pass

if is_speech_available():
 from transformers import EncodecFeatureExtractor, MusicgenProcessor


SCREAMING_SNAKE_CASE_    :       Dict       =							random.Random()
def 							__lowerCAmelCase			(UpperCAmelCase_ ,     UpperCAmelCase_=1.0 ,     UpperCAmelCase_=None ,     UpperCAmelCase_=None		):


    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







@require_torch
@require_sentencepiece
class 		__UpperCAmelCase(		unittest.TestCase			):





     """simple docstring"""



     def 					__SCREAMING_SNAKE_CASE		(   self			:							Optional[int]     )      ->      Any:






         """simple docstring"""
         a__  			=							"""facebook/musicgen-small"""
         a__  			=							tempfile.mkdtemp()

     def 					__SCREAMING_SNAKE_CASE		(   self			:							int    ,					**A			:							List[Any]     )      ->      List[str]:






         """simple docstring"""
         return TaTokenizer.from_pretrained(self.checkpoint    ,					**_snake_case     )

     def 					__SCREAMING_SNAKE_CASE		(   self			:							int    ,					**A			:							str     )      ->      Union[str, Any]:






         """simple docstring"""
         return EncodecFeatureExtractor.from_pretrained(self.checkpoint    ,					**_snake_case     )

     def 					__SCREAMING_SNAKE_CASE		(   self			:							List[str]     )      ->      List[str]:






         """simple docstring"""
         shutil.rmtree(self.tmpdirname     )

     def 					__SCREAMING_SNAKE_CASE		(   self			:							int     )      ->      Optional[int]:






         """simple docstring"""
         a__  			=							self.get_tokenizer()
         a__  			=							self.get_feature_extractor()

         a__  			=							MusicgenProcessor(tokenizer=_snake_case    ,					feature_extractor=_snake_case     )

         processor.save_pretrained(self.tmpdirname     )
         a__  			=							MusicgenProcessor.from_pretrained(self.tmpdirname     )

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

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

     def 					__SCREAMING_SNAKE_CASE		(   self			:							int     )      ->      List[str]:






         """simple docstring"""
         a__  			=							MusicgenProcessor(tokenizer=self.get_tokenizer()    ,					feature_extractor=self.get_feature_extractor()     )
         processor.save_pretrained(self.tmpdirname     )

         a__  			=							self.get_tokenizer(bos_token="""(BOS)"""    ,					eos_token="""(EOS)"""     )
         a__  			=							self.get_feature_extractor(do_normalize=_snake_case    ,					padding_value=1.0     )

         a__  			=							MusicgenProcessor.from_pretrained(
             self.tmpdirname    ,					bos_token="""(BOS)"""    ,					eos_token="""(EOS)"""    ,					do_normalize=_snake_case    ,					padding_value=1.0     )

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

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

     def 					__SCREAMING_SNAKE_CASE		(   self			:							List[str]     )      ->      Tuple:






         """simple docstring"""
         a__  			=							self.get_feature_extractor()
         a__  			=							self.get_tokenizer()

         a__  			=							MusicgenProcessor(tokenizer=_snake_case    ,					feature_extractor=_snake_case     )

         a__  			=							floats_list((3, 10_00)     )

         a__  			=							feature_extractor(_snake_case    ,					return_tensors="""np"""     )
         a__  			=							processor(_snake_case    ,					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 					__SCREAMING_SNAKE_CASE		(   self			:							Any     )      ->      Union[str, Any]:






         """simple docstring"""
         a__  			=							self.get_feature_extractor()
         a__  			=							self.get_tokenizer()

         a__  			=							MusicgenProcessor(tokenizer=_snake_case    ,					feature_extractor=_snake_case     )

         a__  			=							"""This is a test string"""

         a__  			=							processor(text=_snake_case     )

         a__  			=							tokenizer(_snake_case     )

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

     def 					__SCREAMING_SNAKE_CASE		(   self			:							Optional[Any]     )      ->      Optional[int]:






         """simple docstring"""
         a__  			=							self.get_feature_extractor()
         a__  			=							self.get_tokenizer()

         a__  			=							MusicgenProcessor(tokenizer=_snake_case    ,					feature_extractor=_snake_case     )

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

         a__  			=							processor.batch_decode(sequences=_snake_case     )
         a__  			=							tokenizer.batch_decode(_snake_case     )

         self.assertListEqual(_snake_case    ,					_snake_case     )

     def 					__SCREAMING_SNAKE_CASE		(   self			:							Any     )      ->      Optional[int]:






         """simple docstring"""
         a__  			=							self.get_feature_extractor()
         a__  			=							self.get_tokenizer()

         a__  			=							MusicgenProcessor(tokenizer=_snake_case    ,					feature_extractor=_snake_case     )

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






     def 					__SCREAMING_SNAKE_CASE		(   self			:							Tuple     )      ->      Union[str, Any]:






         """simple docstring"""
         a__  			=							self.get_feature_extractor(padding_side="""left"""     )
         a__  			=							self.get_tokenizer()

         a__  			=							MusicgenProcessor(tokenizer=_snake_case    ,					feature_extractor=_snake_case     )

         a__  			=							[floats_list((1, x)     )[0] for x in range(5    ,					20    ,					5     )]
         a__  			=							processor(_snake_case     ).padding_mask

         a__  			=							np.asarray(floats_list((3, 20)     )     )[:, None, :]
         a__  			=							processor.batch_decode(_snake_case    ,					padding_mask=_snake_case     )

         self.assertIsInstance(_snake_case    ,					_snake_case     )

         for audio in decoded_audios:
             self.assertIsInstance(_snake_case    ,					np.ndarray     )

         self.assertTrue(decoded_audios[0].shape == (1, 10)     )
         self.assertTrue(decoded_audios[1].shape == (1, 15)     )
         self.assertTrue(decoded_audios[2].shape == (1, 20)     )












import os
from typing import List, Union

import tensorflow as tf
from tensorflow_text import BertTokenizer as BertTokenizerLayer
from tensorflow_text import FastBertTokenizer, ShrinkLongestTrimmer, case_fold_utfa, combine_segments, pad_model_inputs

from .tokenization_bert import BertTokenizer







class __snake_case     (     tf.keras.layers.Layer						):







   def __init__( self						:		Optional[int]   ,		_snake_case						:		List   ,		_snake_case						:		bool   ,		_snake_case						:		int = None   ,		_snake_case						:		int = None   ,		_snake_case						:		int = None   ,		_snake_case						:		str = "longest"   ,		_snake_case						:		bool = True   ,		_snake_case						:		int = 512   ,		_snake_case						:		int = None   ,		_snake_case						:		bool = True   ,		_snake_case						:		bool = True   ,		_snake_case						:		bool = True   ,		**_snake_case						:		Any   ,		):

        """simple docstring"""


        super().__init__()
        if use_fast_bert_tokenizer:
             UpperCAmelCase_		=				FastBertTokenizer(
                 _snake_case   ,		token_out_type=tf.intaa   ,		lower_case_nfd_strip_accents=_snake_case   ,		**_snake_case)
        else:
             UpperCAmelCase_		=				tf.lookup.StaticVocabularyTable(
                 tf.lookup.KeyValueTensorInitializer(
                     keys=_snake_case   ,		key_dtype=tf.string   ,		values=tf.range(tf.size(_snake_case   ,		out_type=tf.intaa)   ,		dtype=tf.intaa)   ,		value_dtype=tf.intaa   ,		)   ,		num_oov_buckets=1   ,		)
             UpperCAmelCase_		=				BertTokenizerLayer(
                 _snake_case   ,		token_out_type=tf.intaa   ,		lower_case=_snake_case   ,		**_snake_case)

        UpperCAmelCase_		=				vocab_list
        UpperCAmelCase_		=				do_lower_case
        UpperCAmelCase_		=				cls_token_id or vocab_list.index('''[CLS]''')
        UpperCAmelCase_		=				sep_token_id or vocab_list.index('''[SEP]''')
        UpperCAmelCase_		=				pad_token_id or vocab_list.index('''[PAD]''')
        UpperCAmelCase_		=				ShrinkLongestTrimmer(max_length - 3   ,		axis=1)  # Allow room for special tokens
        UpperCAmelCase_		=				max_length
        UpperCAmelCase_		=				padding
        UpperCAmelCase_		=				truncation
        UpperCAmelCase_		=				pad_to_multiple_of
        UpperCAmelCase_		=				return_token_type_ids
        UpperCAmelCase_		=				return_attention_mask







   @classmethod
   def lowerCamelCase		( cls						:		Optional[Any]   ,		_snake_case						:		"PreTrainedTokenizerBase"   ,		**_snake_case						:		str):  # noqa: F821

        """simple docstring"""


        UpperCAmelCase_		=				kwargs.pop('''do_lower_case'''   ,		_snake_case)
        UpperCAmelCase_		=				tokenizer.do_lower_case if do_lower_case is None else do_lower_case
        UpperCAmelCase_		=				kwargs.pop('''cls_token_id'''   ,		_snake_case)
        UpperCAmelCase_		=				tokenizer.cls_token_id if cls_token_id is None else cls_token_id
        UpperCAmelCase_		=				kwargs.pop('''sep_token_id'''   ,		_snake_case)
        UpperCAmelCase_		=				tokenizer.sep_token_id if sep_token_id is None else sep_token_id
        UpperCAmelCase_		=				kwargs.pop('''pad_token_id'''   ,		_snake_case)
        UpperCAmelCase_		=				tokenizer.pad_token_id if pad_token_id is None else pad_token_id

        UpperCAmelCase_		=				tokenizer.get_vocab()
        UpperCAmelCase_		=				sorted([(wordpiece, idx) for wordpiece, idx in vocab.items()]   ,		key=lambda _snake_case: x[1])
        UpperCAmelCase_		=				[entry[0] for entry in vocab]
        return cls(
            vocab_list=_snake_case   ,		do_lower_case=_snake_case   ,		cls_token_id=_snake_case   ,		sep_token_id=_snake_case   ,		pad_token_id=_snake_case   ,		**_snake_case   ,		)







   @classmethod
   def lowerCamelCase		( cls						:		List[str]   ,		_snake_case						:		Union[str, os.PathLike]   ,		*_snake_case						:		Union[str, Any]   ,		**_snake_case						:		Union[str, Any]):

        """simple docstring"""


        try:
             UpperCAmelCase_		=				BertTokenizer.from_pretrained(_snake_case   ,		*_snake_case   ,		**_snake_case)
        except:  # noqa: E722
             from .tokenization_bert_fast import BertTokenizerFast

             UpperCAmelCase_		=				BertTokenizerFast.from_pretrained(_snake_case   ,		*_snake_case   ,		**_snake_case)
        return cls.from_tokenizer(_snake_case   ,		**_snake_case)







   def lowerCamelCase		( self						:		int   ,		_snake_case						:		str):

        """simple docstring"""


        if self.do_lower_case:
             UpperCAmelCase_		=				case_fold_utfa(_snake_case)
        UpperCAmelCase_		=				self.tf_tokenizer.tokenize(_snake_case)
        return tokens.merge_dims(1   ,		-1)







   def lowerCamelCase		( self						:		int   ,		_snake_case						:		str   ,		_snake_case						:		str=None   ,		_snake_case						:		Union[str, Any]=None   ,		_snake_case						:		str=None   ,		_snake_case						:		int=None   ,		_snake_case						:		Optional[int]=None   ,		_snake_case						:		Optional[Any]=None   ,		_snake_case						:		List[str]=None   ,		):

        """simple docstring"""


        if padding is None:
             UpperCAmelCase_		=				self.padding
        if padding not in ("longest", "max_length"):
             raise ValueError('''Padding must be either \'longest\' or \'max_length\'!''')
        if max_length is not None and text_pair is not None:
             # Because we have to instantiate a Trimmer to do it properly
             raise ValueError('''max_length cannot be overridden at call time when truncating paired texts!''')
        if max_length is None:
             UpperCAmelCase_		=				self.max_length
        if truncation is None:
             UpperCAmelCase_		=				self.truncation
        if pad_to_multiple_of is None:
             UpperCAmelCase_		=				self.pad_to_multiple_of
        if return_token_type_ids is None:
             UpperCAmelCase_		=				self.return_token_type_ids
        if return_attention_mask is None:
             UpperCAmelCase_		=				self.return_attention_mask
        if not isinstance(_snake_case   ,		tf.Tensor):
             UpperCAmelCase_		=				tf.convert_to_tensor(_snake_case)
        if text_pair is not None and not isinstance(_snake_case   ,		tf.Tensor):
             UpperCAmelCase_		=				tf.convert_to_tensor(_snake_case)
        if text_pair is not None:
             if text.shape.rank > 1:
                  raise ValueError('''text argument should not be multidimensional when a text pair is supplied!''')
             if text_pair.shape.rank > 1:
                  raise ValueError('''text_pair should not be multidimensional!''')
        if text.shape.rank == 2:
             UpperCAmelCase_	,			UpperCAmelCase_		=				text[:, 0], text[:, 1]
        UpperCAmelCase_		=				self.unpaired_tokenize(_snake_case)
        if text_pair is None:  # Unpaired text
             if truncation:
                  UpperCAmelCase_		=				text[:, : max_length - 2]  # Allow room for special tokens
             UpperCAmelCase_	,			UpperCAmelCase_		=				combine_segments(
                 (text,)   ,		start_of_sequence_id=self.cls_token_id   ,		end_of_segment_id=self.sep_token_id)
        else:  # Paired text
             UpperCAmelCase_		=				self.unpaired_tokenize(_snake_case)
             if truncation:
                  UpperCAmelCase_	,			UpperCAmelCase_		=				self.paired_trimmer.trim([text, text_pair])
             UpperCAmelCase_	,			UpperCAmelCase_		=				combine_segments(
                 (text, text_pair)   ,		start_of_sequence_id=self.cls_token_id   ,		end_of_segment_id=self.sep_token_id)
        if padding == "longest":
             UpperCAmelCase_		=				input_ids.bounding_shape(axis=1)
             if pad_to_multiple_of is not None:
                  # No ceiling division in tensorflow, so we negate floordiv instead
                  UpperCAmelCase_		=				pad_to_multiple_of * (-tf.math.floordiv(-pad_length   ,		_snake_case))
        else:
             UpperCAmelCase_		=				max_length

        UpperCAmelCase_	,			UpperCAmelCase_		=				pad_model_inputs(_snake_case   ,		max_seq_length=_snake_case   ,		pad_value=self.pad_token_id)
        UpperCAmelCase_		=				{'''input_ids''': input_ids}
        if return_attention_mask:
             UpperCAmelCase_		=				attention_mask
        if return_token_type_ids:
             UpperCAmelCase_	,			UpperCAmelCase_		=				pad_model_inputs(
                 _snake_case   ,		max_seq_length=_snake_case   ,		pad_value=self.pad_token_id)
             UpperCAmelCase_		=				token_type_ids
        return output







   def lowerCamelCase		( self						:		Optional[Any]):

        """simple docstring"""


        return {
            "vocab_list": self.vocab_list,
            "do_lower_case": self.do_lower_case,
            "cls_token_id": self.cls_token_id,
            "sep_token_id": self.sep_token_id,
            "pad_token_id": self.pad_token_id,
        }






