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

__lowercase							 =					logging.get_logger(__name__)


@add_end_docstrings(UpperCAmelCase_ )
class 	lowerCamelCase_     (   UpperCAmelCase_ ):






    '''simple docstring'''






    def __init__(	self , **__lowercase)       ->	int:
        super().__init__(**__lowercase)

        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 , __lowercase , **__lowercase)       ->	Union[str, Any]:
        return super().__call__(__lowercase , **__lowercase)







    def 			UpperCamelCase__   (	self , **__lowercase)       ->	int:
        __UpperCamelCase     :int			  =		{}
        if "candidate_labels" in kwargs:
            __UpperCamelCase     :Union[str, Any]			  =		kwargs['''candidate_labels''']
        if "hypothesis_template" in kwargs:
            __UpperCamelCase     :List[str]			  =		kwargs['''hypothesis_template''']

        return preprocess_params, {}, {}







    def 			UpperCamelCase__   (	self , __lowercase , __lowercase=None , __lowercase="This is a photo of {}.")       ->	List[Any]:
        __UpperCamelCase     :Dict			  =		load_image(__lowercase)
        __UpperCamelCase     :Dict			  =		self.image_processor(images=[image] , return_tensors=self.framework)
        __UpperCamelCase     :Optional[int]			  =		candidate_labels
        __UpperCamelCase     :int			  =		[hypothesis_template.format(__lowercase) for x in candidate_labels]
        __UpperCamelCase     :Optional[Any]			  =		self.tokenizer(__lowercase , return_tensors=self.framework , padding=__lowercase)
        __UpperCamelCase     :List[str]			  =		[text_inputs]
        return inputs







    def 			UpperCamelCase__   (	self , __lowercase)       ->	List[str]:
        __UpperCamelCase     :List[str]			  =		model_inputs.pop('''candidate_labels''')
        __UpperCamelCase     :List[str]			  =		model_inputs.pop('''text_inputs''')
        if isinstance(text_inputs[0] , __lowercase):
            __UpperCamelCase     :int			  =		text_inputs[0]
        else:
            # Batching case.
            __UpperCamelCase     :str			  =		text_inputs[0][0]

        __UpperCamelCase     :Dict			  =		self.model(**__lowercase , **__lowercase)

        __UpperCamelCase     :str			  =		{
            '''candidate_labels''': candidate_labels,
            '''logits''': outputs.logits_per_image,
        }
        return model_outputs







    def 			UpperCamelCase__   (	self , __lowercase)       ->	Union[str, Any]:
        __UpperCamelCase     :Optional[Any]			  =		model_outputs.pop('''candidate_labels''')
        __UpperCamelCase     :List[Any]			  =		model_outputs['''logits'''][0]
        if self.framework == "pt":
            __UpperCamelCase     :Tuple			  =		logits.softmax(dim=-1).squeeze(-1)
            __UpperCamelCase     :Optional[int]			  =		probs.tolist()
            if not isinstance(__lowercase , __lowercase):
                __UpperCamelCase     :Dict			  =		[scores]
        elif self.framework == "tf":
            __UpperCamelCase     :Optional[Any]			  =		stable_softmax(__lowercase , axis=-1)
            __UpperCamelCase     :Dict			  =		probs.numpy().tolist()
        else:
            raise ValueError(f"""Unsupported framework: {self.framework}""")

        __UpperCamelCase     :Optional[int]			  =		[
            {'''score''': score, '''label''': candidate_label}
            for score, candidate_label in sorted(zip(__lowercase , __lowercase) , key=lambda __lowercase: -x[0])
        ]
        return result






import json
from typing import TYPE_CHECKING, List, Optional, Tuple

from tokenizers import pre_tokenizers

from ...tokenization_utils_base import BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging


if TYPE_CHECKING:
    from transformers.pipelines.conversational import Conversation


__lowercase							 =					logging.get_logger(__name__)

__lowercase							 =					{'''tokenizer_file''': '''tokenizer.json'''}

__lowercase							 =					{
    '''tokenizer_file''': {
        '''bigscience/tokenizer''': '''https://huggingface.co/bigscience/tokenizer/blob/main/tokenizer.json''',
        '''bigscience/bloom-560m''': '''https://huggingface.co/bigscience/bloom-560m/blob/main/tokenizer.json''',
        '''bigscience/bloom-1b1''': '''https://huggingface.co/bigscience/bloom-1b1/blob/main/tokenizer.json''',
        '''bigscience/bloom-1b7''': '''https://huggingface.co/bigscience/bloom-1b7/blob/main/tokenizer.json''',
        '''bigscience/bloom-3b''': '''https://huggingface.co/bigscience/bloom-3b/blob/main/tokenizer.json''',
        '''bigscience/bloom-7b1''': '''https://huggingface.co/bigscience/bloom-7b1/blob/main/tokenizer.json''',
        '''bigscience/bloom''': '''https://huggingface.co/bigscience/bloom/blob/main/tokenizer.json''',
    },
}


class 	lowerCamelCase_     (   UpperCAmelCase_ ):






    '''simple docstring'''






    a__	:						int						=      VOCAB_FILES_NAMES
    a__	:						Tuple						=      PRETRAINED_VOCAB_FILES_MAP
    a__	:						List[str]						=      ["""input_ids""", """attention_mask"""]
    a__	:						int						=      None







    def __init__(	self , __lowercase=None , __lowercase=None , __lowercase=None , __lowercase="<unk>" , __lowercase="<s>" , __lowercase="</s>" , __lowercase="<pad>" , __lowercase=False , __lowercase=False , **__lowercase , )       ->	List[str]:
        super().__init__(
            __lowercase , __lowercase , tokenizer_file=__lowercase , unk_token=__lowercase , bos_token=__lowercase , eos_token=__lowercase , pad_token=__lowercase , add_prefix_space=__lowercase , clean_up_tokenization_spaces=__lowercase , **__lowercase , )
        __UpperCamelCase     :int			  =		json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__())
        if pre_tok_state.get('''add_prefix_space''' , __lowercase) != add_prefix_space:
            __UpperCamelCase     :Any			  =		getattr(__lowercase , pre_tok_state.pop('''type'''))
            __UpperCamelCase     :str			  =		add_prefix_space
            __UpperCamelCase     :List[str]			  =		pre_tok_class(**__lowercase)

        __UpperCamelCase     :Tuple			  =		add_prefix_space







    def 			UpperCamelCase__   (	self , *__lowercase , **__lowercase)       ->	BatchEncoding:
        __UpperCamelCase     :Tuple			  =		kwargs.get('''is_split_into_words''' , __lowercase)
        if not (self.add_prefix_space or not is_split_into_words):
            raise Exception(
                f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with"""
                ''' pretokenized inputs.''')

        return super()._batch_encode_plus(*__lowercase , **__lowercase)







    def 			UpperCamelCase__   (	self , *__lowercase , **__lowercase)       ->	BatchEncoding:
        __UpperCamelCase     :List[str]			  =		kwargs.get('''is_split_into_words''' , __lowercase)

        if not (self.add_prefix_space or not is_split_into_words):
            raise Exception(
                f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with"""
                ''' pretokenized inputs.''')

        return super()._encode_plus(*__lowercase , **__lowercase)







    def 			UpperCamelCase__   (	self , __lowercase , __lowercase = None)       ->	Tuple[str]:
        __UpperCamelCase     :Optional[Any]			  =		self._tokenizer.model.save(__lowercase , name=__lowercase)
        return tuple(__lowercase)







    def 			UpperCamelCase__   (	self , __lowercase)       ->	List[int]:
        __UpperCamelCase     :str			  =		[]
        for is_user, text in conversation.iter_texts():
            input_ids.extend(self.encode(__lowercase , add_special_tokens=__lowercase) + [self.eos_token_id])

        if len(__lowercase) > self.model_max_length:
            __UpperCamelCase     :Any			  =		input_ids[-self.model_max_length :]
        return input_ids





