






from collections import UserDict
from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
		from PIL import Image

		from ..image_utils import load_image

if is_torch_available():
		from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING

if is_tf_available():
		from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
		from ..tf_utils import stable_softmax

UpperCamelCase			    =     logging.get_logger(__name__)



@add_end_docstrings(_UpperCAmelCase   )
class 				__UpperCAmelCase		(_UpperCAmelCase   ):







			def __init__(     self:  List[Any]				,     **UpperCAmelCase_:  int					):







									'''simple docstring'''




									super().__init__(**UpperCAmelCase_					)

									requires_backends(self				,     """vision"""					)
									self.check_model_type(
									    TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
									    if self.framework == """tf"""
									    else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING					)







			def __call__(     self:  Optional[int]				,     UpperCAmelCase_:  Union[str, List[str], "Image", List["Image"]]				,     **UpperCAmelCase_:  List[str]					):







									'''simple docstring'''




									return super().__call__(UpperCAmelCase_				,     **UpperCAmelCase_					)







			def 							UpperCamelCase				(     self:  List[str]				,     **UpperCAmelCase_:  List[str]					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  {}
									if "candidate_labels" in kwargs:
															_SCREAMING_SNAKE_CASE     				=  kwargs["""candidate_labels"""]
									if "hypothesis_template" in kwargs:
															_SCREAMING_SNAKE_CASE     				=  kwargs["""hypothesis_template"""]

									return preprocess_params, {}, {}







			def 							UpperCamelCase				(     self:  Union[str, Any]				,     UpperCAmelCase_:  Tuple				,     UpperCAmelCase_:  List[str]=None				,     UpperCAmelCase_:  int="This is a photo of {}."					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  load_image(UpperCAmelCase_					)
									_SCREAMING_SNAKE_CASE     				=  self.image_processor(images=[image]				,     return_tensors=self.framework					)
									_SCREAMING_SNAKE_CASE     				=  candidate_labels
									_SCREAMING_SNAKE_CASE     				=  [hypothesis_template.format(UpperCAmelCase_					) for x in candidate_labels]
									_SCREAMING_SNAKE_CASE     				=  self.tokenizer(UpperCAmelCase_				,     return_tensors=self.framework				,     padding=UpperCAmelCase_					)
									_SCREAMING_SNAKE_CASE     				=  [text_inputs]
									return inputs







			def 							UpperCamelCase				(     self:  Dict				,     UpperCAmelCase_:  Optional[int]					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  model_inputs.pop("""candidate_labels"""					)
									_SCREAMING_SNAKE_CASE     				=  model_inputs.pop("""text_inputs"""					)
									if isinstance(text_inputs[0]				,     UpperCAmelCase_					):
															_SCREAMING_SNAKE_CASE     				=  text_inputs[0]
									else:
															# Batching case.
															_SCREAMING_SNAKE_CASE     				=  text_inputs[0][0]

									_SCREAMING_SNAKE_CASE     				=  self.model(**UpperCAmelCase_				,     **UpperCAmelCase_					)

									_SCREAMING_SNAKE_CASE     				=  {
									    """candidate_labels""": candidate_labels,
									    """logits""": outputs.logits_per_image,
									}
									return model_outputs







			def 							UpperCamelCase				(     self:  Union[str, Any]				,     UpperCAmelCase_:  Optional[int]					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  model_outputs.pop("""candidate_labels"""					)
									_SCREAMING_SNAKE_CASE     				=  model_outputs["""logits"""][0]
									if self.framework == "pt":
															_SCREAMING_SNAKE_CASE     				=  logits.softmax(dim=-1					).squeeze(-1					)
															_SCREAMING_SNAKE_CASE     				=  probs.tolist()
															if not isinstance(UpperCAmelCase_				,     UpperCAmelCase_					):
																					_SCREAMING_SNAKE_CASE     				=  [scores]
									elif self.framework == "tf":
															_SCREAMING_SNAKE_CASE     				=  stable_softmax(UpperCAmelCase_				,     axis=-1					)
															_SCREAMING_SNAKE_CASE     				=  probs.numpy().tolist()
									else:
															raise ValueError(F'Unsupported framework: {self.framework}'					)

									_SCREAMING_SNAKE_CASE     				=  [
									    {"""score""": score, """label""": candidate_label}
									    for score, candidate_label in sorted(zip(UpperCAmelCase_				,     UpperCAmelCase_					)				,     key=lambda UpperCAmelCase_					: -x[0]					)
									]
									return result









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

from ...tokenization_utils import AddedToken
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging


if is_sentencepiece_available():
		from .tokenization_camembert import CamembertTokenizer
else:
		UpperCamelCase			    =     None


UpperCamelCase			    =     logging.get_logger(__name__)

UpperCamelCase			    =     {'''vocab_file''': '''sentencepiece.bpe.model''', '''tokenizer_file''': '''tokenizer.json'''}

UpperCamelCase			    =     {
    '''vocab_file''': {
        '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model''',
    },
    '''tokenizer_file''': {
        '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/tokenizer.json''',
    },
}

UpperCamelCase			    =     {
    '''camembert-base''': 512,
}

UpperCamelCase			    =     '''▁'''



class 				__UpperCAmelCase		(_UpperCAmelCase   ):
			__snake_case    :				int									=							VOCAB_FILES_NAMES
			__snake_case    :				Any									=							PRETRAINED_VOCAB_FILES_MAP
			__snake_case    :				Optional[Any]									=							PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
			__snake_case    :				Dict									=							["input_ids", "attention_mask"]
			__snake_case    :				Tuple									=							CamembertTokenizer







			def __init__(     self:  List[Any]				,     UpperCAmelCase_:  Optional[int]=None				,     UpperCAmelCase_:  Tuple=None				,     UpperCAmelCase_:  str="<s>"				,     UpperCAmelCase_:  List[str]="</s>"				,     UpperCAmelCase_:  Dict="</s>"				,     UpperCAmelCase_:  List[Any]="<s>"				,     UpperCAmelCase_:  Dict="<unk>"				,     UpperCAmelCase_:  Any="<pad>"				,     UpperCAmelCase_:  Tuple="<mask>"				,     UpperCAmelCase_:  str=["<s>NOTUSED", "</s>NOTUSED"]				,     **UpperCAmelCase_:  Optional[Any]				,     ):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  AddedToken(UpperCAmelCase_				,     lstrip=UpperCAmelCase_				,     rstrip=UpperCAmelCase_					) if isinstance(UpperCAmelCase_				,     UpperCAmelCase_					) else mask_token

									super().__init__(
									    UpperCAmelCase_				,     tokenizer_file=UpperCAmelCase_				,     bos_token=UpperCAmelCase_				,     eos_token=UpperCAmelCase_				,     sep_token=UpperCAmelCase_				,     cls_token=UpperCAmelCase_				,     unk_token=UpperCAmelCase_				,     pad_token=UpperCAmelCase_				,     mask_token=UpperCAmelCase_				,     additional_special_tokens=UpperCAmelCase_				,     **UpperCAmelCase_				,     )

									_SCREAMING_SNAKE_CASE     				=  vocab_file
									_SCREAMING_SNAKE_CASE     				=  False if not self.vocab_file else True







			def 							UpperCamelCase				(     self:  int				,     UpperCAmelCase_:  List[int]				,     UpperCAmelCase_:  Optional[List[int]] = None					):







									'''simple docstring'''




									if token_ids_a is None:
															return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
									_SCREAMING_SNAKE_CASE     				=  [self.cls_token_id]
									_SCREAMING_SNAKE_CASE     				=  [self.sep_token_id]
									return cls + token_ids_a + sep + sep + token_ids_a + sep







			def 							UpperCamelCase				(     self:  List[str]				,     UpperCAmelCase_:  List[int]				,     UpperCAmelCase_:  Optional[List[int]] = None					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  [self.sep_token_id]
									_SCREAMING_SNAKE_CASE     				=  [self.cls_token_id]

									if token_ids_a is None:
															return len(cls + token_ids_a + sep					) * [0]
									return len(cls + token_ids_a + sep + sep + token_ids_a + sep					) * [0]







			def 							UpperCamelCase				(     self:  List[str]				,     UpperCAmelCase_:  str				,     UpperCAmelCase_:  Optional[str] = None					):







									'''simple docstring'''




									if not self.can_save_slow_tokenizer:
															raise ValueError(
															    """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """
															    """tokenizer."""					)

									if not os.path.isdir(UpperCAmelCase_					):
															logger.error(F'Vocabulary path ({save_directory}) should be a directory'					)
															return
									_SCREAMING_SNAKE_CASE     				=  os.path.join(
									    UpperCAmelCase_				,     (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]					)

									if os.path.abspath(self.vocab_file					) != os.path.abspath(UpperCAmelCase_					):
															copyfile(self.vocab_file				,     UpperCAmelCase_					)

									return (out_vocab_file,)

