
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(__lowercase   )
class 		UpperCamelCase__  (	__lowercase   ):
   def __init__(self			: Any ,    **snake_case_			: Any       ):
    super().__init__(**snake_case_       )

    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			: str ,    snake_case_			: Union[str, List[str], "Image", List["Image"]] ,    **snake_case_			: Optional[Any]       ):
    return super().__call__(snake_case_ ,    **snake_case_       )
   def 				lowerCAmelCase      (self			: int ,    **snake_case_			: Optional[int]       ):
    __a			:  List[str]		    =  {}
    if "candidate_labels" in kwargs:
     __a			:  str		    =  kwargs['''candidate_labels''']
    if "hypothesis_template" in kwargs:
     __a			:  int		    =  kwargs['''hypothesis_template''']

    return preprocess_params, {}, {}
   def 				lowerCAmelCase      (self			: Tuple ,    snake_case_			: Dict ,    snake_case_			: str=None ,    snake_case_			: List[Any]="This is a photo of {}."       ):
    __a			:  Dict		    =  load_image(snake_case_       )
    __a			:  str		    =  self.image_processor(images=[image] ,    return_tensors=self.framework       )
    __a			:  Any		    =  candidate_labels
    __a			:  Tuple		    =  [hypothesis_template.format(snake_case_       ) for x in candidate_labels]
    __a			:  Tuple		    =  self.tokenizer(snake_case_ ,    return_tensors=self.framework ,    padding=snake_case_       )
    __a			:  List[Any]		    =  [text_inputs]
    return inputs
   def 				lowerCAmelCase      (self			: Dict ,    snake_case_			: Tuple       ):
    __a			:  Union[str, Any]		    =  model_inputs.pop('''candidate_labels'''       )
    __a			:  Union[str, Any]		    =  model_inputs.pop('''text_inputs'''       )
    if isinstance(text_inputs[0] ,    snake_case_       ):
     __a			:  Optional[Any]		    =  text_inputs[0]
    else:
     # Batching case.
     __a			:  Any		    =  text_inputs[0][0]

    __a			:  List[str]		    =  self.model(**snake_case_ ,    **snake_case_       )

    __a			:  List[str]		    =  {
        '''candidate_labels''': candidate_labels,
        '''logits''': outputs.logits_per_image,
    }
    return model_outputs







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

    __a			:  List[str]		    =  [
        {'''score''': score, '''label''': candidate_label}
        for score, candidate_label in sorted(zip(snake_case_ ,    snake_case_       ) ,    key=lambda snake_case_       : -x[0]       )
    ]
    return result


import os
import unittest

from transformers.models.phobert.tokenization_phobert import VOCAB_FILES_NAMES, PhobertTokenizer

from ...test_tokenization_common import TokenizerTesterMixin



class 		UpperCamelCase__  (	__lowercase   ,unittest.TestCase   ):
   _SCREAMING_SNAKE_CASE				:							Union[str, Any]     	=				PhobertTokenizer
   _SCREAMING_SNAKE_CASE				:							int     	=				False
   def 				lowerCAmelCase      (self			: Optional[int]       ):
    super().setUp()

    # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
    __a			:  Optional[int]		    =  ['''T@@''', '''i''', '''I''', '''R@@''', '''r''', '''e@@''']
    __a			:  Tuple		    =  dict(zip(snake_case_ ,    range(len(snake_case_       )       )       )       )
    __a			:  int		    =  ['''#version: 0.2''', '''l à</w>''']
    __a			:  List[Any]		    =  {'''unk_token''': '''<unk>'''}

    __a			:  Any		    =  os.path.join(self.tmpdirname ,    VOCAB_FILES_NAMES['''vocab_file''']       )
    __a			:  List[Any]		    =  os.path.join(self.tmpdirname ,    VOCAB_FILES_NAMES['''merges_file''']       )

    with open(self.vocab_file ,    '''w''' ,    encoding='''utf-8'''       ) as fp:
     for token in vocab_tokens:
      fp.write(f"{token} {vocab_tokens[token]}\n"       )
    with open(self.merges_file ,    '''w''' ,    encoding='''utf-8'''       ) as fp:
     fp.write('''\n'''.join(snake_case_       )       )
   def 				lowerCAmelCase      (self			: Union[str, Any] ,    **snake_case_			: List[str]       ):
    kwargs.update(self.special_tokens_map       )
    return PhobertTokenizer.from_pretrained(self.tmpdirname ,    **snake_case_       )
   def 				lowerCAmelCase      (self			: Any ,    snake_case_			: Dict       ):
    __a			:  Union[str, Any]		    =  '''Tôi là VinAI Research'''
    __a			:  int		    =  '''T<unk> i <unk> <unk> <unk> <unk> <unk> <unk> I Re<unk> e<unk> <unk> <unk> <unk>'''
    return input_text, output_text







   def 				lowerCAmelCase      (self			: Optional[Any]       ):
    __a			:  Optional[int]		    =  PhobertTokenizer(self.vocab_file ,    self.merges_file ,    **self.special_tokens_map       )
    __a			:  Any		    =  '''Tôi là VinAI Research'''
    __a			:  Union[str, Any]		    =  '''T@@ ô@@ i l@@ à V@@ i@@ n@@ A@@ I R@@ e@@ s@@ e@@ a@@ r@@ c@@ h'''.split()
    __a			:  List[str]		    =  tokenizer.tokenize(snake_case_       )
    print(snake_case_       )
    self.assertListEqual(snake_case_ ,    snake_case_       )

    __a			:  str		    =  tokens + [tokenizer.unk_token]

    __a			:  str		    =  [4, 3, 5, 3, 3, 3, 3, 3, 3, 6, 7, 9, 3, 9, 3, 3, 3, 3, 3]
    self.assertListEqual(tokenizer.convert_tokens_to_ids(snake_case_       ) ,    snake_case_       )
