




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

_lowerCamelCase     :		int								=       logging.get_logger(__name__)


@add_end_docstrings(UpperCAmelCase__					)
class     UpperCamelCase_   (			UpperCAmelCase__					):

    '''simple docstring'''






    def __init__(      self				:     int ,			**UpperCAmelCase__				:     Dict)						->Optional[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				:     str ,			UpperCAmelCase__				:     Union[str, List[str], "Image", List["Image"]] ,			**UpperCAmelCase__				:     Tuple)						->List[str]:





           '''simple docstring'''

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


    def 	SCREAMING_SNAKE_CASE							(      self				:     str ,			**UpperCAmelCase__				:     int)						->Optional[Any]:





           '''simple docstring'''

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

           return preprocess_params, {}, {}


    def 	SCREAMING_SNAKE_CASE							(      self				:     Optional[int] ,			UpperCAmelCase__				:     Optional[int] ,			UpperCAmelCase__				:     Optional[Any]=None ,			UpperCAmelCase__				:     int="This is a photo of {}.")						->Dict:





           '''simple docstring'''

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


    def 	SCREAMING_SNAKE_CASE							(      self				:     Tuple ,			UpperCAmelCase__				:     Tuple)						->Dict:





           '''simple docstring'''

           A__							=   model_inputs.pop('''candidate_labels''')
           A__							=   model_inputs.pop('''text_inputs''')
           if isinstance(text_inputs[0] ,			UpperCAmelCase__):
                  A__							=   text_inputs[0]
           else:
                  # Batching case.
                  A__							=   text_inputs[0][0]

           A__							=   self.model(**UpperCAmelCase__ ,			**UpperCAmelCase__)

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





    def 	SCREAMING_SNAKE_CASE							(      self				:     Optional[Any] ,			UpperCAmelCase__				:     List[Any])						->str:





           '''simple docstring'''

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

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








# This script creates a super tiny model that is useful inside tests, when we just want to test that
# the machinery works, without needing to the check the quality of the outcomes.
#
# This version creates a tiny model through reduction of a normal pre-trained model, but keeping the
# full vocab, merges file, and thus also resulting in a larger model due to a large vocab size.
# This gives ~3MB in total for all files.
#
# If you want a 50 times smaller than this see `fsmt-make-super-tiny-model.py`, which is slightly more complicated
#
#
# It will be used then as "stas/tiny-wmt19-en-de"

# Build
from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration

_lowerCamelCase     :		Optional[Any]								=       """facebook/wmt19-en-de"""
_lowerCamelCase     :		Optional[Any]								=       FSMTTokenizer.from_pretrained(mname)
# get the correct vocab sizes, etc. from the master model
_lowerCamelCase     :		int								=       FSMTConfig.from_pretrained(mname)
config.update(
    dict(
        d_model=4,
        encoder_layers=1,
        decoder_layers=1,
        encoder_ffn_dim=4,
        decoder_ffn_dim=4,
        encoder_attention_heads=1,
        decoder_attention_heads=1,
    )
)

_lowerCamelCase     :		Union[str, Any]								=       FSMTForConditionalGeneration(config)
print(F'''num of params {tiny_model.num_parameters()}''')

# Test
_lowerCamelCase     :		int								=       tokenizer(["""Making tiny model"""], return_tensors="""pt""")
_lowerCamelCase     :		int								=       tiny_model(**batch)

print("""test output:""", len(outputs.logits[0]))

# Save
_lowerCamelCase     :		str								=       """tiny-wmt19-en-de"""
tiny_model.half()  # makes it smaller
tiny_model.save_pretrained(mname_tiny)
tokenizer.save_pretrained(mname_tiny)

print(F'''Generated {mname_tiny}''')

# Upload
# transformers-cli upload tiny-wmt19-en-de


