

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



@add_end_docstrings(UpperCAmelCase_     )
class   __lowercase    (			UpperCAmelCase_     ):




			"""simple docstring"""







			def __init__(			self  :					int       ,						**lowerCAmelCase__  :					List[str]):
									super().__init__(**lowerCAmelCase__)

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



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Tuple       ,						**lowerCAmelCase__  :					Optional[Any]):
									SCREAMING_SNAKE_CASE_:			List[str]  		=	{}
									if "candidate_labels" in kwargs:
															SCREAMING_SNAKE_CASE_:			Optional[int]  		=	kwargs["candidate_labels"]
									if "hypothesis_template" in kwargs:
															SCREAMING_SNAKE_CASE_:			List[str]  		=	kwargs["hypothesis_template"]

									return preprocess_params, {}, {}



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



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Tuple       ,						lowerCAmelCase__  :					Optional[int]):
									SCREAMING_SNAKE_CASE_:			Any  		=	model_inputs.pop("candidate_labels")
									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	model_inputs.pop("text_inputs")
									if isinstance(text_inputs[0]       ,						lowerCAmelCase__):
															SCREAMING_SNAKE_CASE_:			List[Any]  		=	text_inputs[0]
									else:
															# Batching case.
															SCREAMING_SNAKE_CASE_:			Tuple  		=	text_inputs[0][0]

									SCREAMING_SNAKE_CASE_:			str  		=	self.model(**lowerCAmelCase__       ,						**lowerCAmelCase__)

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




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

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









import unittest
from queue import Empty
from threading import Thread

from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available
from transformers.testing_utils import CaptureStdout, require_torch, torch_device

from ..test_modeling_common import ids_tensor


if is_torch_available():
						import torch

						from transformers import AutoModelForCausalLM



@require_torch
class   __lowercase    (			unittest.TestCase     ):




			"""simple docstring"""







			def 	_SCREAMING_SNAKE_CASE      (			self  :					int):
									SCREAMING_SNAKE_CASE_:			str  		=	AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
									SCREAMING_SNAKE_CASE_:			str  		=	AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			str  		=	-1

									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	ids_tensor((1, 5)       ,						vocab_size=model.config.vocab_size).to(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			Any  		=	model.generate(lowerCAmelCase__       ,						max_new_tokens=10       ,						do_sample=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			List[str]  		=	tokenizer.decode(greedy_ids[0])

									with CaptureStdout() as cs:
															SCREAMING_SNAKE_CASE_:			int  		=	TextStreamer(lowerCAmelCase__)
															model.generate(lowerCAmelCase__       ,						max_new_tokens=10       ,						do_sample=lowerCAmelCase__       ,						streamer=lowerCAmelCase__)
									# The greedy text should be printed to stdout, except for the final "\n" in the streamer
									SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	cs.out[:-1]

									self.assertEqual(lowerCAmelCase__       ,						lowerCAmelCase__)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					int):
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
									SCREAMING_SNAKE_CASE_:			int  		=	AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	-1

									SCREAMING_SNAKE_CASE_:			int  		=	ids_tensor((1, 5)       ,						vocab_size=model.config.vocab_size).to(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			int  		=	model.generate(lowerCAmelCase__       ,						max_new_tokens=10       ,						do_sample=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			Tuple  		=	tokenizer.decode(greedy_ids[0])

									SCREAMING_SNAKE_CASE_:			int  		=	TextIteratorStreamer(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	{"input_ids": input_ids, "max_new_tokens": 10, "do_sample": False, "streamer": streamer}
									SCREAMING_SNAKE_CASE_:			Tuple  		=	Thread(target=model.generate       ,						kwargs=lowerCAmelCase__)
									thread.start()
									SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	""
									for new_text in streamer:
															streamer_text += new_text

									self.assertEqual(lowerCAmelCase__       ,						lowerCAmelCase__)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Optional[int]):
									SCREAMING_SNAKE_CASE_:			int  		=	AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
									SCREAMING_SNAKE_CASE_:			int  		=	AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	-1

									SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	ids_tensor((1, 5)       ,						vocab_size=model.config.vocab_size).to(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			Dict  		=	model.generate(lowerCAmelCase__       ,						max_new_tokens=10       ,						do_sample=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			Tuple  		=	greedy_ids[:, input_ids.shape[1] :]
									SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	tokenizer.decode(new_greedy_ids[0])

									with CaptureStdout() as cs:
															SCREAMING_SNAKE_CASE_:			Dict  		=	TextStreamer(lowerCAmelCase__       ,						skip_prompt=lowerCAmelCase__)
															model.generate(lowerCAmelCase__       ,						max_new_tokens=10       ,						do_sample=lowerCAmelCase__       ,						streamer=lowerCAmelCase__)
									# The greedy text should be printed to stdout, except for the final "\n" in the streamer
									SCREAMING_SNAKE_CASE_:			Any  		=	cs.out[:-1]

									self.assertEqual(lowerCAmelCase__       ,						lowerCAmelCase__)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Tuple):
									# Tests that we can pass `decode_kwargs` to the streamer to control how the tokens are decoded. Must be tested
									# with actual models -- the dummy models' tokenizers are not aligned with their models, and
									# `skip_special_tokens=True` has no effect on them
									SCREAMING_SNAKE_CASE_:			Tuple  		=	AutoTokenizer.from_pretrained("distilgpt2")
									SCREAMING_SNAKE_CASE_:			List[str]  		=	AutoModelForCausalLM.from_pretrained("distilgpt2").to(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	-1

									SCREAMING_SNAKE_CASE_:			List[str]  		=	torch.ones((1, 5)       ,						device=lowerCAmelCase__).long() * model.config.bos_token_id
									with CaptureStdout() as cs:
															SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	TextStreamer(lowerCAmelCase__       ,						skip_special_tokens=lowerCAmelCase__)
															model.generate(lowerCAmelCase__       ,						max_new_tokens=1       ,						do_sample=lowerCAmelCase__       ,						streamer=lowerCAmelCase__)

									# The prompt contains a special token, so the streamer should not print it. As such, the output text, when
									# re-tokenized, must only contain one token
									SCREAMING_SNAKE_CASE_:			str  		=	cs.out[:-1]  # Remove the final "\n"
									SCREAMING_SNAKE_CASE_:			Tuple  		=	tokenizer(lowerCAmelCase__       ,						return_tensors="pt")
									self.assertEqual(streamer_text_tokenized.input_ids.shape       ,						(1, 1))




			def 	_SCREAMING_SNAKE_CASE      (			self  :					Optional[Any]):
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
									SCREAMING_SNAKE_CASE_:			List[str]  		=	AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			Dict  		=	-1

									SCREAMING_SNAKE_CASE_:			List[str]  		=	ids_tensor((1, 5)       ,						vocab_size=model.config.vocab_size).to(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			Any  		=	TextIteratorStreamer(lowerCAmelCase__       ,						timeout=0.001)
									SCREAMING_SNAKE_CASE_:			Any  		=	{"input_ids": input_ids, "max_new_tokens": 10, "do_sample": False, "streamer": streamer}
									SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	Thread(target=model.generate       ,						kwargs=lowerCAmelCase__)
									thread.start()

									# The streamer will timeout after 0.001 seconds, so an exception will be raised
									with self.assertRaises(lowerCAmelCase__):
															SCREAMING_SNAKE_CASE_:			Tuple  		=	""
															for new_text in streamer:
																					streamer_text += new_text






