'''simple docstring'''


import shutil
import tempfile
import unittest
from pathlib import Path
from shutil import copyfile

from transformers import SpeechaTextTokenizer, is_speech_available
from transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB_FILES_NAMES, save_json
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, require_torchaudio
from transformers.utils import FEATURE_EXTRACTOR_NAME

from .test_feature_extraction_speech_to_text import floats_list


if is_speech_available():
 from transformers import SpeechaTextFeatureExtractor, SpeechaTextProcessor


snake_case__	:     str      =    get_tests_dir('''fixtures/test_sentencepiece.model''')






@require_torch
@require_torchaudio
@require_sentencepiece
class 	__SCREAMING_SNAKE_CASE		(			unittest.TestCase			):







  '''simple docstring'''






  def _UpperCamelCase	(					self		):




       '''simple docstring'''

       UpperCAmelCase_				:  Optional[int]  = tempfile.mkdtemp()

       UpperCAmelCase_				:  Union[str, Any]  = ['<s>', '<pad>', '</s>', '<unk>', '▁This', '▁is', '▁a', '▁t', 'est']
       UpperCAmelCase_				:  Tuple  = dict(zip(snake_case_ ,						range(len(snake_case_		)		)		)		)
       UpperCAmelCase_				:  Tuple  = Path(self.tmpdirname		)
       save_json(snake_case_ ,						save_dir / VOCAB_FILES_NAMES['vocab_file']		)
       if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists():
            copyfile(snake_case_ ,						save_dir / VOCAB_FILES_NAMES['spm_file']		)

       UpperCAmelCase_				:  List[str]  = SpeechaTextTokenizer.from_pretrained(self.tmpdirname		)
       tokenizer.save_pretrained(self.tmpdirname		)

       UpperCAmelCase_				:  str  = {
           'feature_size': 2_4,
           'num_mel_bins': 2_4,
           'padding_value': 0.0,
           'sampling_rate': 1_6_0_0_0,
           'return_attention_mask': False,
           'do_normalize': True,
       }
       save_json(snake_case_ ,						save_dir / FEATURE_EXTRACTOR_NAME		)


  def _UpperCamelCase	(					self ,						**snake_case_		):




       '''simple docstring'''

       return SpeechaTextTokenizer.from_pretrained(self.tmpdirname ,						**snake_case_		)


  def _UpperCamelCase	(					self ,						**snake_case_		):




       '''simple docstring'''

       return SpeechaTextFeatureExtractor.from_pretrained(self.tmpdirname ,						**snake_case_		)


  def _UpperCamelCase	(					self		):




       '''simple docstring'''

       shutil.rmtree(self.tmpdirname		)


  def _UpperCamelCase	(					self		):




       '''simple docstring'''

       UpperCAmelCase_				:  int  = self.get_tokenizer()
       UpperCAmelCase_				:  int  = self.get_feature_extractor()

       UpperCAmelCase_				:  List[str]  = SpeechaTextProcessor(tokenizer=snake_case_ ,						feature_extractor=snake_case_		)

       processor.save_pretrained(self.tmpdirname		)
       UpperCAmelCase_				:  Dict  = SpeechaTextProcessor.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 _UpperCamelCase	(					self		):




       '''simple docstring'''

       UpperCAmelCase_				:  Tuple  = SpeechaTextProcessor(
           tokenizer=self.get_tokenizer() ,						feature_extractor=self.get_feature_extractor()		)
       processor.save_pretrained(self.tmpdirname		)

       UpperCAmelCase_				:  Optional[Any]  = self.get_tokenizer(bos_token='(BOS)' ,						eos_token='(EOS)'		)
       UpperCAmelCase_				:  Union[str, Any]  = self.get_feature_extractor(do_normalize=snake_case_ ,						padding_value=1.0		)

       UpperCAmelCase_				:  Any  = SpeechaTextProcessor.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 _UpperCamelCase	(					self		):




       '''simple docstring'''

       UpperCAmelCase_				:  List[Any]  = self.get_feature_extractor()
       UpperCAmelCase_				:  Union[str, Any]  = self.get_tokenizer()

       UpperCAmelCase_				:  Union[str, Any]  = SpeechaTextProcessor(tokenizer=snake_case_ ,						feature_extractor=snake_case_		)

       UpperCAmelCase_				:  List[Any]  = floats_list((3, 1_0_0_0)		)

       UpperCAmelCase_				:  Union[str, Any]  = feature_extractor(snake_case_ ,						return_tensors='np'		)
       UpperCAmelCase_				:  Any  = 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 _UpperCamelCase	(					self		):




       '''simple docstring'''

       UpperCAmelCase_				:  Union[str, Any]  = self.get_feature_extractor()
       UpperCAmelCase_				:  Tuple  = self.get_tokenizer()

       UpperCAmelCase_				:  Tuple  = SpeechaTextProcessor(tokenizer=snake_case_ ,						feature_extractor=snake_case_		)

       UpperCAmelCase_				:  Tuple  = 'This is a test string'

       UpperCAmelCase_				:  List[str]  = processor(text=snake_case_		)

       UpperCAmelCase_				:  Optional[int]  = tokenizer(snake_case_		)

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


  def _UpperCamelCase	(					self		):




       '''simple docstring'''

       UpperCAmelCase_				:  Optional[Any]  = self.get_feature_extractor()
       UpperCAmelCase_				:  Dict  = self.get_tokenizer()

       UpperCAmelCase_				:  Any  = SpeechaTextProcessor(tokenizer=snake_case_ ,						feature_extractor=snake_case_		)

       UpperCAmelCase_				:  Dict  = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

       UpperCAmelCase_				:  str  = processor.batch_decode(snake_case_		)
       UpperCAmelCase_				:  Union[str, Any]  = tokenizer.batch_decode(snake_case_		)

       self.assertListEqual(snake_case_ ,						snake_case_		)






  def _UpperCamelCase	(					self		):




       '''simple docstring'''

       UpperCAmelCase_				:  Optional[Any]  = self.get_feature_extractor()
       UpperCAmelCase_				:  Union[str, Any]  = self.get_tokenizer()

       UpperCAmelCase_				:  int  = SpeechaTextProcessor(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' ,						)













"""simple docstring"""





import argparse
import logging

import datasets
from tokenizers import Tokenizer, decoders, normalizers, pre_tokenizers, processors
from tokenizers.models import Unigram
from tokenizers.trainers import UnigramTrainer

from transformers import AlbertTokenizerFast


lowerCAmelCase__        =      logging.getLogger(__name__)


def    a__       (       ):




		"""simple docstring"""


		UpperCamelCase =						argparse.ArgumentParser(description="Train a unigram tokenizer on the wikitext dataset."     )
		parser.add_argument(
		    "--dataset_name"	,						type=_SCREAMING_SNAKE_CASE	,						default="wikitext"	,						help="Name of the training. Explore datasets at: hf.co/datasets."	,						)
		parser.add_argument(
		    "--dataset_config"	,						type=_SCREAMING_SNAKE_CASE	,						default="wikitext-103-raw-v1"	,						help="Configuration name of the dataset."     )
		parser.add_argument(
		    "--batch_size"	,						type=_SCREAMING_SNAKE_CASE	,						default=1_000	,						help="Batch size during training."	,						)
		parser.add_argument(
		    "--vocab_size"	,						type=_SCREAMING_SNAKE_CASE	,						default=10_048	,						help="Size of the desired vocabulary."	,						)
		parser.add_argument(
		    "--limit"	,						default=_SCREAMING_SNAKE_CASE	,						type=_SCREAMING_SNAKE_CASE	,						help="Limit the number of shards (used for debugging)."	,						)
		parser.add_argument(
		    "--export_to_hub"	,						action="store_true"	,						)

		UpperCamelCase =						parser.parse_args()
		return args


def    a__       (       _SCREAMING_SNAKE_CASE     ):




		"""simple docstring"""


		UpperCamelCase =						datasets.load_dataset(args.dataset_name	,						args.dataset_config	,						split="train"     )

		if args.limit is not None:
				UpperCamelCase =						min(len(_SCREAMING_SNAKE_CASE     )	,						args.limit     )
				UpperCamelCase =						dataset.select(range(_SCREAMING_SNAKE_CASE     )     )
				logger.info(F"Limiting the dataset to {args.limit} entries."     )

		def batch_iterator():
				for i in range(0	,						len(_SCREAMING_SNAKE_CASE     )	,						args.batch_size     ):
						yield dataset[i : i + args.batch_size]["text"]

    # Prepare the tokenizer.
		UpperCamelCase =						Tokenizer(Unigram()     )
		UpperCamelCase =						normalizers.Sequence([normalizers.Replace("``"	,						"\""     ), normalizers.Replace("''"	,						"\""     )]     )
		UpperCamelCase =						pre_tokenizers.Metaspace()

		# Prepare the trainer.
		UpperCamelCase =						UnigramTrainer(
		    unk_token="<unk>"	,						special_tokens=["[CLS]", "[SEP]", "<unk>", "<pad>", "[MASK]"]	,						vocab_size=args.vocab_size	,						)

		logger.info("Training the tokenizer."     )
		tokenizer.train_from_iterator(batch_iterator()	,						trainer=_SCREAMING_SNAKE_CASE     )
		logger.info("Tokenizer training complete!"     )

		UpperCamelCase =						tokenizer.token_to_id("[CLS]"     )
		UpperCamelCase =						tokenizer.token_to_id("[SEP]"     )
		UpperCamelCase =						processors.TemplateProcessing(
		    single="[CLS]:0 $A:0 [SEP]:0"	,						pair="[CLS]:0 $A:0 [SEP]:0 $B:1 [SEP]:1"	,						special_tokens=[
		        ("[CLS]", cls_token_id),
		        ("[SEP]", sep_token_id),
		    ]	,						)
		UpperCamelCase =						decoders.Metaspace()

		if args.export_to_hub:
				logger.info("Exporting the trained tokenzier to Hub."     )
				UpperCamelCase =						AlbertTokenizerFast(tokenizer_object=_SCREAMING_SNAKE_CASE     )
				new_tokenizer.push_to_hub("unigram-tokenizer-dataset"     )


if __name__ == "__main__":
						lowerCAmelCase__        =      parse_args()
						main(args)






