


"""simple docstring"""


import unittest

from transformers import is_vision_available
from transformers.pipelines import pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
		from PIL import Image
else:







		class 				lowerCAmelCase_				:



								'''simple docstring'''


								@staticmethod
								def 						_SCREAMING_SNAKE_CASE      ( *A_     :      str  ,**A_     :      Tuple      )     ->   str:
									pass







@is_pipeline_test
@require_vision
class 				lowerCAmelCase_				(      unittest.TestCase    ):



						'''simple docstring'''


						@require_torch
						def 						_SCREAMING_SNAKE_CASE      ( self     :      Optional[Any]      )     ->   Optional[int]:
							A						   =   pipeline(
							    model='hf-internal-testing/tiny-random-clip-zero-shot-image-classification'  ,)
							A						   =   Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'      )
							A						   =   image_classifier(A_  ,candidate_labels=['a', 'b', 'c']      )

							# The floating scores are so close, we enter floating error approximation and the order is not guaranteed across
							# python and torch versions.
							self.assertIn(
							    nested_simplify(A_      )  ,[
							        [{'score': 0.3_33, 'label': 'a'}, {'score': 0.3_33, 'label': 'b'}, {'score': 0.3_33, 'label': 'c'}],
							        [{'score': 0.3_33, 'label': 'a'}, {'score': 0.3_33, 'label': 'c'}, {'score': 0.3_33, 'label': 'b'}],
							    ]  ,)

							A						   =   image_classifier([image] * 5  ,candidate_labels=['A', 'B', 'C']  ,batch_size=2      )
							self.assertEqual(
							    nested_simplify(A_      )  ,[
							        [
							            {'score': 0.3_33, 'label': ANY(A_      )},
							            {'score': 0.3_33, 'label': ANY(A_      )},
							            {'score': 0.3_33, 'label': ANY(A_      )},
							        ],
							        [
							            {'score': 0.3_33, 'label': ANY(A_      )},
							            {'score': 0.3_33, 'label': ANY(A_      )},
							            {'score': 0.3_33, 'label': ANY(A_      )},
							        ],
							        [
							            {'score': 0.3_33, 'label': ANY(A_      )},
							            {'score': 0.3_33, 'label': ANY(A_      )},
							            {'score': 0.3_33, 'label': ANY(A_      )},
							        ],
							        [
							            {'score': 0.3_33, 'label': ANY(A_      )},
							            {'score': 0.3_33, 'label': ANY(A_      )},
							            {'score': 0.3_33, 'label': ANY(A_      )},
							        ],
							        [
							            {'score': 0.3_33, 'label': ANY(A_      )},
							            {'score': 0.3_33, 'label': ANY(A_      )},
							            {'score': 0.3_33, 'label': ANY(A_      )},
							        ],
							    ]  ,)


						@require_tf
						def 						_SCREAMING_SNAKE_CASE      ( self     :      Any      )     ->   str:
							A						   =   pipeline(
							    model='hf-internal-testing/tiny-random-clip-zero-shot-image-classification'  ,framework='tf'      )
							A						   =   Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'      )
							A						   =   image_classifier(A_  ,candidate_labels=['a', 'b', 'c']      )

							self.assertEqual(
							    nested_simplify(A_      )  ,[{'score': 0.3_33, 'label': 'a'}, {'score': 0.3_33, 'label': 'b'}, {'score': 0.3_33, 'label': 'c'}]  ,)

							A						   =   image_classifier([image] * 5  ,candidate_labels=['A', 'B', 'C']  ,batch_size=2      )
							self.assertEqual(
							    nested_simplify(A_      )  ,[
							        [
							            {'score': 0.3_33, 'label': ANY(A_      )},
							            {'score': 0.3_33, 'label': ANY(A_      )},
							            {'score': 0.3_33, 'label': ANY(A_      )},
							        ],
							        [
							            {'score': 0.3_33, 'label': ANY(A_      )},
							            {'score': 0.3_33, 'label': ANY(A_      )},
							            {'score': 0.3_33, 'label': ANY(A_      )},
							        ],
							        [
							            {'score': 0.3_33, 'label': ANY(A_      )},
							            {'score': 0.3_33, 'label': ANY(A_      )},
							            {'score': 0.3_33, 'label': ANY(A_      )},
							        ],
							        [
							            {'score': 0.3_33, 'label': ANY(A_      )},
							            {'score': 0.3_33, 'label': ANY(A_      )},
							            {'score': 0.3_33, 'label': ANY(A_      )},
							        ],
							        [
							            {'score': 0.3_33, 'label': ANY(A_      )},
							            {'score': 0.3_33, 'label': ANY(A_      )},
							            {'score': 0.3_33, 'label': ANY(A_      )},
							        ],
							    ]  ,)


						@slow
						@require_torch
						def 						_SCREAMING_SNAKE_CASE      ( self     :      Any      )     ->   List[Any]:
							A						   =   pipeline(
							    task='zero-shot-image-classification'  ,model='openai/clip-vit-base-patch32'  ,)
							# This is an image of 2 cats with remotes and no planes
							A						   =   Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'      )
							A						   =   image_classifier(A_  ,candidate_labels=['cat', 'plane', 'remote']      )

							self.assertEqual(
							    nested_simplify(A_      )  ,[
							        {'score': 0.5_11, 'label': 'remote'},
							        {'score': 0.4_85, 'label': 'cat'},
							        {'score': 0.0_04, 'label': 'plane'},
							    ]  ,)

							A						   =   image_classifier([image] * 5  ,candidate_labels=['cat', 'plane', 'remote']  ,batch_size=2      )
							self.assertEqual(
							    nested_simplify(A_      )  ,[
							        [
							            {'score': 0.5_11, 'label': 'remote'},
							            {'score': 0.4_85, 'label': 'cat'},
							            {'score': 0.0_04, 'label': 'plane'},
							        ],
							    ]
							    * 5  ,)




						@slow
						@require_tf
						def 						_SCREAMING_SNAKE_CASE      ( self     :      Dict      )     ->   Tuple:
							A						   =   pipeline(
							    task='zero-shot-image-classification'  ,model='openai/clip-vit-base-patch32'  ,framework='tf'      )
							# This is an image of 2 cats with remotes and no planes
							A						   =   Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'      )
							A						   =   image_classifier(A_  ,candidate_labels=['cat', 'plane', 'remote']      )
							self.assertEqual(
							    nested_simplify(A_      )  ,[
							        {'score': 0.5_11, 'label': 'remote'},
							        {'score': 0.4_85, 'label': 'cat'},
							        {'score': 0.0_04, 'label': 'plane'},
							    ]  ,)

							A						   =   image_classifier([image] * 5  ,candidate_labels=['cat', 'plane', 'remote']  ,batch_size=2      )
							self.assertEqual(
							    nested_simplify(A_      )  ,[
							        [
							            {'score': 0.5_11, 'label': 'remote'},
							            {'score': 0.4_85, 'label': 'cat'},
							            {'score': 0.0_04, 'label': 'plane'},
							        ],
							    ]
							    * 5  ,)

"""simple docstring"""


import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


_lowercase							   =				logging.get_logger(__name__)

_lowercase							   =				{'''vocab_file''': '''spm_char.model'''}

_lowercase							   =				{
    '''vocab_file''': {
        '''microsoft/speecht5_asr''': '''https://huggingface.co/microsoft/speecht5_asr/resolve/main/spm_char.model''',
        '''microsoft/speecht5_tts''': '''https://huggingface.co/microsoft/speecht5_tts/resolve/main/spm_char.model''',
        '''microsoft/speecht5_vc''': '''https://huggingface.co/microsoft/speecht5_vc/resolve/main/spm_char.model''',
    }
}

_lowercase							   =				{
    '''microsoft/speecht5_asr''': 10_24,
    '''microsoft/speecht5_tts''': 10_24,
    '''microsoft/speecht5_vc''': 10_24,
}







class 				lowerCAmelCase_				(      _lowercase    ):



						'''simple docstring'''


						_lowerCamelCase:    Optional[Any]      =    VOCAB_FILES_NAMES
						_lowerCamelCase:    List[Any]      =    PRETRAINED_VOCAB_FILES_MAP
						_lowerCamelCase:    str      =    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
						_lowerCamelCase:    Tuple      =    ['''input_ids''', '''attention_mask''']


						def __init__( self     :      List[str]  ,A_     :      int  ,A_     :      List[str]="<s>"  ,A_     :      Optional[Any]="</s>"  ,A_     :      Optional[Any]="<unk>"  ,A_     :      str="<pad>"  ,A_     :      Optional[Dict[str, Any]] = None  ,**A_     :      List[str]  ,)     ->   None:
							A						   =   {} if sp_model_kwargs is None else sp_model_kwargs

							super().__init__(
							    bos_token=A_  ,eos_token=A_  ,unk_token=A_  ,pad_token=A_  ,sp_model_kwargs=self.sp_model_kwargs  ,**A_  ,)

							A						   =   vocab_file

							A						   =   spm.SentencePieceProcessor(**self.sp_model_kwargs      )
							self.sp_model.Load(A_      )


						@property
						def 						_SCREAMING_SNAKE_CASE      ( self     :      Any      )     ->   str:
							return self.sp_model.get_piece_size()


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Optional[int]      )     ->   Optional[Any]:
							A						   =   {self.convert_ids_to_tokens(A_      ): i for i in range(self.vocab_size      )}
							vocab.update(self.added_tokens_encoder      )
							return vocab


						def __getstate__( self     :      str      )     ->   Any:
							A						   =   self.__dict__.copy()
							A						   =   None
							return state


						def __setstate__( self     :      Optional[int]  ,A_     :      str      )     ->   Tuple:
							A						   =   d

							# for backward compatibility
							if not hasattr(self  ,'sp_model_kwargs'      ):
								A						   =   {}

							A						   =   spm.SentencePieceProcessor(**self.sp_model_kwargs      )
							self.sp_model.Load(self.vocab_file      )


						def 						_SCREAMING_SNAKE_CASE      ( self     :      str  ,A_     :      str      )     ->   List[str]:
							return self.sp_model.encode(A_  ,out_type=A_      )


						def 						_SCREAMING_SNAKE_CASE      ( self     :      List[str]  ,A_     :      Union[str, Any]      )     ->   Union[str, Any]:
							return self.sp_model.piece_to_id(A_      )


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Optional[Any]  ,A_     :      Dict      )     ->   List[Any]:
							A						   =   self.sp_model.IdToPiece(A_      )
							return token


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Tuple  ,A_     :      Optional[Any]      )     ->   List[str]:
							A						   =   []
							A						   =   ''
							for token in tokens:
								# make sure that special tokens are not decoded using sentencepiece model
								if token in self.all_special_tokens:
									out_string += self.sp_model.decode(A_      ) + token
									A						   =   []
								else:
									current_sub_tokens.append(A_      )
							out_string += self.sp_model.decode(A_      )
							return out_string.strip()


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Dict  ,A_     :      Dict  ,A_     :      Optional[int]=None      )     ->   List[int]:
							if token_ids_a is None:
								return token_ids_a + [self.eos_token_id]
							# We don't expect to process pairs, but leave the pair logic for API consistency
							return token_ids_a + token_ids_a + [self.eos_token_id]


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Optional[Any]  ,A_     :      List[int]  ,A_     :      Optional[List[int]] = None  ,A_     :      bool = False      )     ->   List[int]:
							if already_has_special_tokens:
								return super().get_special_tokens_mask(
								    token_ids_a=A_  ,token_ids_a=A_  ,already_has_special_tokens=A_      )

							A						   =   [1]
							if token_ids_a is None:
								return ([0] * len(A_      )) + suffix_ones
							return ([0] * len(A_      )) + ([0] * len(A_      )) + suffix_ones




						def 						_SCREAMING_SNAKE_CASE      ( self     :      str  ,A_     :      str  ,A_     :      Optional[str] = None      )     ->   Tuple[str]:
							if not os.path.isdir(A_      ):
								logger.error(F'Vocabulary path ({save_directory}) should be a directory'      )
								return
							A						   =   os.path.join(
							    A_  ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']      )

							if os.path.abspath(self.vocab_file      ) != os.path.abspath(A_      ) and os.path.isfile(self.vocab_file      ):
								copyfile(self.vocab_file  ,A_      )
							elif not os.path.isfile(self.vocab_file      ):
								with open(A_  ,'wb'      ) as fi:
									A						   =   self.sp_model.serialized_model_proto()
									fi.write(A_      )

							return (out_vocab_file,)