






'''simple docstring'''




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__          =						logging.get_logger(__name__)







@add_end_docstrings(__lowerCamelCase    )
class       __lowercase					(__lowerCamelCase    ):

	def __init__(      self   :						List[str]  ,					**UpperCAmelCase_   :						Any):
			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_   :						Dict):
			return super().__call__(UpperCAmelCase_  ,					**UpperCAmelCase_)

	def      __UpperCamelCase							(      self   :						List[Any]  ,					**UpperCAmelCase_   :						Dict):
			UpperCamelCase__				:					List[str]					=					{}
			if "candidate_labels" in kwargs:
					UpperCamelCase__				:					Dict					=					kwargs['candidate_labels']
			if "hypothesis_template" in kwargs:
					UpperCamelCase__				:					Tuple					=					kwargs['hypothesis_template']

			return preprocess_params, {}, {}

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

	def      __UpperCamelCase							(      self   :						str  ,					UpperCAmelCase_   :						List[str]):
			UpperCamelCase__				:					Union[str, Any]					=					model_inputs.pop('candidate_labels')
			UpperCamelCase__				:					Optional[Any]					=					model_inputs.pop('text_inputs')
			if isinstance(text_inputs[0]  ,					UpperCAmelCase_):
					UpperCamelCase__				:					List[str]					=					text_inputs[0]
			else:
					# Batching case.
					UpperCamelCase__				:					List[Any]					=					text_inputs[0][0]

			UpperCamelCase__				:					Dict					=					self.model(**UpperCAmelCase_  ,					**UpperCAmelCase_)

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





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

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












'''simple docstring'''




import json
import os
import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import CLIPTokenizer, CLIPTokenizerFast
from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available


if is_vision_available():
		from PIL import Image

		from transformers import CLIPImageProcessor, CLIPProcessor







@require_vision
class       __lowercase					(unittest.TestCase    ):

	def      __UpperCamelCase							(      self   :						List[Any]):
			UpperCamelCase__				:					int					=					tempfile.mkdtemp()

			# fmt: off
			UpperCamelCase__				:					Union[str, Any]					=					['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>']
			# fmt: on
			UpperCamelCase__				:					Dict					=					dict(zip(UpperCAmelCase_  ,					range(len(UpperCAmelCase_))))
			UpperCamelCase__				:					Optional[Any]					=					['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', '']
			UpperCamelCase__				:					Union[str, Any]					=					{'unk_token': '<unk>'}

			UpperCamelCase__				:					Union[str, Any]					=					os.path.join(self.tmpdirname  ,					VOCAB_FILES_NAMES['vocab_file'])
			UpperCamelCase__				:					Optional[Any]					=					os.path.join(self.tmpdirname  ,					VOCAB_FILES_NAMES['merges_file'])
			with open(self.vocab_file  ,					'w'  ,					encoding='utf-8') as fp:
					fp.write(json.dumps(UpperCAmelCase_) + '\n')
			with open(self.merges_file  ,					'w'  ,					encoding='utf-8') as fp:
					fp.write('\n'.join(UpperCAmelCase_))

			UpperCamelCase__				:					Dict					=					{
			    'do_resize': True,
			    'size': 20,
			    'do_center_crop': True,
			    'crop_size': 18,
			    'do_normalize': True,
			    'image_mean': [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73],
			    'image_std': [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11],
			}
			UpperCamelCase__				:					Any					=					os.path.join(self.tmpdirname  ,					UpperCAmelCase_)
			with open(self.image_processor_file  ,					'w'  ,					encoding='utf-8') as fp:
					json.dump(UpperCAmelCase_  ,					UpperCAmelCase_)

	def      __UpperCamelCase							(      self   :						Dict  ,					**UpperCAmelCase_   :						Union[str, Any]):
			return CLIPTokenizer.from_pretrained(self.tmpdirname  ,					**UpperCAmelCase_)

	def      __UpperCamelCase							(      self   :						Optional[int]  ,					**UpperCAmelCase_   :						str):
			return CLIPTokenizerFast.from_pretrained(self.tmpdirname  ,					**UpperCAmelCase_)

	def      __UpperCamelCase							(      self   :						Optional[Any]  ,					**UpperCAmelCase_   :						Union[str, Any]):
			return CLIPImageProcessor.from_pretrained(self.tmpdirname  ,					**UpperCAmelCase_)

	def      __UpperCamelCase							(      self   :						str):
			shutil.rmtree(self.tmpdirname)

	def      __UpperCamelCase							(      self   :						Tuple):
			UpperCamelCase__				:					List[str]					=					[np.random.randint(255  ,					size=(3, 30, 400)  ,					dtype=np.uinta)]

			UpperCamelCase__				:					List[str]					=					[Image.fromarray(np.moveaxis(UpperCAmelCase_  ,					0  ,					-1)) for x in image_inputs]

			return image_inputs

	def      __UpperCamelCase							(      self   :						Dict):
			UpperCamelCase__				:					Union[str, Any]					=					self.get_tokenizer()
			UpperCamelCase__				:					Optional[Any]					=					self.get_rust_tokenizer()
			UpperCamelCase__				:					Any					=					self.get_image_processor()

			UpperCamelCase__				:					str					=					CLIPProcessor(tokenizer=UpperCAmelCase_  ,					image_processor=UpperCAmelCase_)
			processor_slow.save_pretrained(self.tmpdirname)
			UpperCamelCase__				:					Any					=					CLIPProcessor.from_pretrained(self.tmpdirname  ,					use_fast=UpperCAmelCase_)

			UpperCamelCase__				:					str					=					CLIPProcessor(tokenizer=UpperCAmelCase_  ,					image_processor=UpperCAmelCase_)
			processor_fast.save_pretrained(self.tmpdirname)
			UpperCamelCase__				:					Optional[int]					=					CLIPProcessor.from_pretrained(self.tmpdirname)

			self.assertEqual(processor_slow.tokenizer.get_vocab()  ,					tokenizer_slow.get_vocab())
			self.assertEqual(processor_fast.tokenizer.get_vocab()  ,					tokenizer_fast.get_vocab())
			self.assertEqual(tokenizer_slow.get_vocab()  ,					tokenizer_fast.get_vocab())
			self.assertIsInstance(processor_slow.tokenizer  ,					UpperCAmelCase_)
			self.assertIsInstance(processor_fast.tokenizer  ,					UpperCAmelCase_)

			self.assertEqual(processor_slow.image_processor.to_json_string()  ,					image_processor.to_json_string())
			self.assertEqual(processor_fast.image_processor.to_json_string()  ,					image_processor.to_json_string())
			self.assertIsInstance(processor_slow.image_processor  ,					UpperCAmelCase_)
			self.assertIsInstance(processor_fast.image_processor  ,					UpperCAmelCase_)

	def      __UpperCamelCase							(      self   :						List[str]):
			UpperCamelCase__				:					Union[str, Any]					=					CLIPProcessor(tokenizer=self.get_tokenizer()  ,					image_processor=self.get_image_processor())
			processor.save_pretrained(self.tmpdirname)

			UpperCamelCase__				:					List[str]					=					self.get_tokenizer(bos_token='(BOS)'  ,					eos_token='(EOS)')
			UpperCamelCase__				:					Tuple					=					self.get_image_processor(do_normalize=UpperCAmelCase_  ,					padding_value=1.0)

			UpperCamelCase__				:					Dict					=					CLIPProcessor.from_pretrained(
			    self.tmpdirname  ,					bos_token='(BOS)'  ,					eos_token='(EOS)'  ,					do_normalize=UpperCAmelCase_  ,					padding_value=1.0)

			self.assertEqual(processor.tokenizer.get_vocab()  ,					tokenizer_add_kwargs.get_vocab())
			self.assertIsInstance(processor.tokenizer  ,					UpperCAmelCase_)

			self.assertEqual(processor.image_processor.to_json_string()  ,					image_processor_add_kwargs.to_json_string())
			self.assertIsInstance(processor.image_processor  ,					UpperCAmelCase_)

	def      __UpperCamelCase							(      self   :						Dict):
			UpperCamelCase__				:					Optional[Any]					=					self.get_image_processor()
			UpperCamelCase__				:					int					=					self.get_tokenizer()

			UpperCamelCase__				:					List[Any]					=					CLIPProcessor(tokenizer=UpperCAmelCase_  ,					image_processor=UpperCAmelCase_)

			UpperCamelCase__				:					int					=					self.prepare_image_inputs()

			UpperCamelCase__				:					int					=					image_processor(UpperCAmelCase_  ,					return_tensors='np')
			UpperCamelCase__				:					Optional[int]					=					processor(images=UpperCAmelCase_  ,					return_tensors='np')

			for key in input_image_proc.keys():
					self.assertAlmostEqual(input_image_proc[key].sum()  ,					input_processor[key].sum()  ,					delta=1e-2)

	def      __UpperCamelCase							(      self   :						Dict):
			UpperCamelCase__				:					Optional[Any]					=					self.get_image_processor()
			UpperCamelCase__				:					Dict					=					self.get_tokenizer()

			UpperCamelCase__				:					List[Any]					=					CLIPProcessor(tokenizer=UpperCAmelCase_  ,					image_processor=UpperCAmelCase_)

			UpperCamelCase__				:					Any					=					'lower newer'

			UpperCamelCase__				:					Union[str, Any]					=					processor(text=UpperCAmelCase_)

			UpperCamelCase__				:					Optional[Any]					=					tokenizer(UpperCAmelCase_)

			for key in encoded_tok.keys():
					self.assertListEqual(encoded_tok[key]  ,					encoded_processor[key])

	def      __UpperCamelCase							(      self   :						int):
			UpperCamelCase__				:					Optional[int]					=					self.get_image_processor()
			UpperCamelCase__				:					List[str]					=					self.get_tokenizer()

			UpperCamelCase__				:					List[Any]					=					CLIPProcessor(tokenizer=UpperCAmelCase_  ,					image_processor=UpperCAmelCase_)

			UpperCamelCase__				:					Optional[Any]					=					'lower newer'
			UpperCamelCase__				:					List[Any]					=					self.prepare_image_inputs()

			UpperCamelCase__				:					str					=					processor(text=UpperCAmelCase_  ,					images=UpperCAmelCase_)

			self.assertListEqual(list(inputs.keys())  ,					['input_ids', 'attention_mask', 'pixel_values'])

			# test if it raises when no input is passed
			with pytest.raises(UpperCAmelCase_):
					processor()

	def      __UpperCamelCase							(      self   :						Dict):
			UpperCamelCase__				:					Any					=					self.get_image_processor()
			UpperCamelCase__				:					Dict					=					self.get_tokenizer()

			UpperCamelCase__				:					Optional[Any]					=					CLIPProcessor(tokenizer=UpperCAmelCase_  ,					image_processor=UpperCAmelCase_)

			UpperCamelCase__				:					Optional[Any]					=					[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

			UpperCamelCase__				:					List[Any]					=					processor.batch_decode(UpperCAmelCase_)
			UpperCamelCase__				:					Optional[int]					=					tokenizer.batch_decode(UpperCAmelCase_)

			self.assertListEqual(UpperCAmelCase_  ,					UpperCAmelCase_)





	def      __UpperCamelCase							(      self   :						str):
			UpperCamelCase__				:					Union[str, Any]					=					self.get_image_processor()
			UpperCamelCase__				:					List[str]					=					self.get_tokenizer()

			UpperCamelCase__				:					Optional[Any]					=					CLIPProcessor(tokenizer=UpperCAmelCase_  ,					image_processor=UpperCAmelCase_)

			UpperCamelCase__				:					List[Any]					=					'lower newer'
			UpperCamelCase__				:					Optional[int]					=					self.prepare_image_inputs()

			UpperCamelCase__				:					List[str]					=					processor(text=UpperCAmelCase_  ,					images=UpperCAmelCase_)

			self.assertListEqual(list(inputs.keys())  ,					processor.model_input_names)




