




"""simple docstring"""



import argparse
import os

import transformers

from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS
from .utils import logging


logging.set_verbosity_info()

SCREAMING_SNAKE_CASE    =	logging.get_logger(__name__)


SCREAMING_SNAKE_CASE    =	{name: getattr(transformers, name + "Fast") for name in SLOW_TO_FAST_CONVERTERS}







def   _SCREAMING_SNAKE_CASE       (							lowercase_      ,			lowercase_      ,			lowercase_      ,			lowercase_						)						->		Any:
 if tokenizer_name is not None and tokenizer_name not in TOKENIZER_CLASSES:
  raise ValueError(f"""Unrecognized tokenizer name, should be one of {list(TOKENIZER_CLASSES.keys()						)}."""						)

 if tokenizer_name is None:
  A__	=    TOKENIZER_CLASSES
 else:
  A__	=    {tokenizer_name: getattr(lowercase_      ,			tokenizer_name + "Fast"						)}

 logger.info(f"""Loading tokenizer classes: {tokenizer_names}"""						)

 for tokenizer_name in tokenizer_names:
  A__	=    TOKENIZER_CLASSES[tokenizer_name]

  A__	=    True
  if checkpoint_name is None:
   A__	=    list(tokenizer_class.max_model_input_sizes.keys()						)
  else:
   A__	=    [checkpoint_name]

  logger.info(f"""For tokenizer {tokenizer_class.__class__.__name__} loading checkpoints: {checkpoint_names}"""						)

  for checkpoint in checkpoint_names:
   logger.info(f"""Loading {tokenizer_class.__class__.__name__} {checkpoint}"""						)

   # Load tokenizer
   A__	=    tokenizer_class.from_pretrained(lowercase_      ,			force_download=lowercase_						)

   # Save fast tokenizer
   logger.info(f"""Save fast tokenizer to {dump_path} with prefix {checkpoint} add_prefix {add_prefix}"""						)

   # For organization names we create sub-directories
   if "/" in checkpoint:
    A__,				A__	=    checkpoint.split("/"						)
    A__	=    os.path.join(lowercase_      ,			lowercase_						)
   elif add_prefix:
    A__	=    checkpoint
    A__	=    dump_path
   else:
    A__	=    None
    A__	=    dump_path

   logger.info(f"""=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}"""						)

   if checkpoint in list(tokenizer.pretrained_vocab_files_map.values()						)[0]:
    A__	=    list(tokenizer.pretrained_vocab_files_map.values()						)[0][checkpoint]
    A__	=    file_path.split(lowercase_						)[-1][0]
    if next_char == "/":
     A__	=    os.path.join(lowercase_      ,			lowercase_						)
     A__	=    None

    logger.info(f"""=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}"""						)

   A__	=    tokenizer.save_pretrained(
       lowercase_      ,			legacy_format=lowercase_      ,			filename_prefix=lowercase_						)
   logger.info(f"""=> File names {file_names}"""						)

   for file_name in file_names:
    if not file_name.endswith("tokenizer.json"						):
     os.remove(lowercase_						)
     logger.info(f"""=> removing {file_name}"""						)


if __name__ == "__main__":
      SCREAMING_SNAKE_CASE    =	argparse.ArgumentParser()
      # Required parameters
      parser.add_argument(
          "--dump_path", default=None, type=str, required=True, help="Path to output generated fast tokenizer files."
      )
      parser.add_argument(
          "--tokenizer_name",
          default=None,
          type=str,
          help=(
              f'Optional tokenizer type selected in the list of {list(TOKENIZER_CLASSES.keys())}. If not given, will '
              "download and convert all the checkpoints from AWS."
          ),
      )
      parser.add_argument(
          "--checkpoint_name",
          default=None,
          type=str,
          help="Optional checkpoint name. If not given, will download and convert the canonical checkpoints from AWS.",
      )
      parser.add_argument(
          "--force_download",
          action="store_true",
          help="Re-download checkpoints.",
      )
      SCREAMING_SNAKE_CASE    =	parser.parse_args()

      convert_slow_checkpoint_to_fast(args.tokenizer_name, args.checkpoint_name, args.dump_path, args.force_download)











"""simple docstring"""



import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import is_speech_available, is_vision_available
from transformers.testing_utils import require_torch


if is_vision_available():
      from transformers import TvltImageProcessor

if is_speech_available():
      from transformers import TvltFeatureExtractor

from transformers import TvltProcessor




@require_torch
class      UpperCAmelCase_  (						unittest.TestCase							):




    def 							__magic_name__							(   self						:	str				)				->							Dict:




     '''simple docstring'''

     A__	=    "ZinengTang/tvlt-base"
     A__	=    tempfile.mkdtemp()




    def 							__magic_name__							(   self						:	int     ,			**snake_case_						:	Dict				)				->							Union[str, Any]:




     '''simple docstring'''

     return TvltImageProcessor.from_pretrained(self.checkpoint     ,			**snake_case_				)




    def 							__magic_name__							(   self						:	Optional[int]     ,			**snake_case_						:	str				)				->							List[str]:




     '''simple docstring'''

     return TvltFeatureExtractor.from_pretrained(self.checkpoint     ,			**snake_case_				)




    def 							__magic_name__							(   self						:	Optional[int]				)				->							str:




     '''simple docstring'''

     shutil.rmtree(self.tmpdirname				)




    def 							__magic_name__							(   self						:	Tuple				)				->							Any:




     '''simple docstring'''

     A__	=    self.get_image_processor()
     A__	=    self.get_feature_extractor()

     A__	=    TvltProcessor(image_processor=snake_case_     ,			feature_extractor=snake_case_				)
     processor.save_pretrained(self.tmpdirname				)
     A__	=    TvltProcessor.from_pretrained(self.tmpdirname				)

     self.assertIsInstance(processor.feature_extractor     ,			snake_case_				)
     self.assertIsInstance(processor.image_processor     ,			snake_case_				)




    def 							__magic_name__							(   self						:	Optional[Any]				)				->							Union[str, Any]:




     '''simple docstring'''

     A__	=    self.get_image_processor()
     A__	=    self.get_feature_extractor()

     A__	=    TvltProcessor(image_processor=snake_case_     ,			feature_extractor=snake_case_				)

     A__	=    np.ones([12_000]				)

     A__	=    feature_extractor(snake_case_     ,			return_tensors="np"				)
     A__	=    processor(audio=snake_case_     ,			return_tensors="np"				)

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




    def 							__magic_name__							(   self						:	Tuple				)				->							Tuple:




     '''simple docstring'''

     A__	=    self.get_image_processor()
     A__	=    self.get_feature_extractor()

     A__	=    TvltProcessor(image_processor=snake_case_     ,			feature_extractor=snake_case_				)

     A__	=    np.ones([3, 224, 224]				)

     A__	=    image_processor(snake_case_     ,			return_tensors="np"				)
     A__	=    processor(images=snake_case_     ,			return_tensors="np"				)

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




    def 							__magic_name__							(   self						:	Tuple				)				->							Optional[int]:




     '''simple docstring'''

     A__	=    self.get_image_processor()
     A__	=    self.get_feature_extractor()

     A__	=    TvltProcessor(image_processor=snake_case_     ,			feature_extractor=snake_case_				)

     A__	=    np.ones([12_000]				)
     A__	=    np.ones([3, 224, 224]				)

     A__	=    processor(audio=snake_case_     ,			images=snake_case_				)

     self.assertListEqual(list(inputs.keys()				)     ,			["audio_values", "audio_mask", "pixel_values", "pixel_mask"]				)

     # test if it raises when no input is passed
     with pytest.raises(snake_case_				):
      processor()




    def 							__magic_name__							(   self						:	Optional[Any]				)				->							Tuple:




     '''simple docstring'''

     A__	=    self.get_image_processor()
     A__	=    self.get_feature_extractor()

     A__	=    TvltProcessor(image_processor=snake_case_     ,			feature_extractor=snake_case_				)

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





