





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

UpperCamelCase__   : Tuple					  = logging.get_logger(__name__)







@add_end_docstrings(A_  )
class   _UpperCamelCase  (       A_  ):







					'''simple docstring'''

					def __init__(						self    :  Optional[Any] ,					**__lowercase    :  Any		):






						'''simple docstring'''







						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    :  Tuple ,					__lowercase    :  Union[str, List[str], "Image", List["Image"]] ,					**__lowercase    :  List[Any]		):






						'''simple docstring'''







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





					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any] ,					**__lowercase    :  Optional[Any]		):






						'''simple docstring'''







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

						return preprocess_params, {}, {}





					def        SCREAMING_SNAKE_CASE							(						self    :  Tuple ,					__lowercase    :  Dict ,					__lowercase    :  List[Any]=None ,					__lowercase    :  int="This is a photo of {}."		):






						'''simple docstring'''







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





					def        SCREAMING_SNAKE_CASE							(						self    :  List[str] ,					__lowercase    :  str		):






						'''simple docstring'''







						UpperCAmelCase_								=     model_inputs.pop("""candidate_labels"""		)
						UpperCAmelCase_								=     model_inputs.pop("""text_inputs"""		)
						if isinstance(text_inputs[0] ,					__lowercase		):
							UpperCAmelCase_								=     text_inputs[0]
						else:
							# Batching case.
							UpperCAmelCase_								=     text_inputs[0][0]

						UpperCAmelCase_								=     self.model(**__lowercase ,					**__lowercase		)

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





					def        SCREAMING_SNAKE_CASE							(						self    :  int ,					__lowercase    :  Tuple		):






						'''simple docstring'''







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

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









import pytest

from datasets import Dataset, DatasetDict, Features, NamedSplit, Value
from datasets.io.text import TextDatasetReader

from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases




def    A_(			A				,      A   ):
	assert isinstance(A				,      A   )
	assert dataset.num_rows == 4
	assert dataset.num_columns == 1
	assert dataset.column_names == ["text"]
	for feature, expected_dtype in expected_features.items():
		assert dataset.features[feature].dtype == expected_dtype




@pytest.mark.parametrize("""keep_in_memory"""				,      [False, True]   )
def    A_(			A				,      A				,      A   ):
	UpperCAmelCase_								=     tmp_path / """cache"""
	UpperCAmelCase_								=     {"""text""": """string"""}
	with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
		UpperCAmelCase_								=     TextDatasetReader(A				,      cache_dir=A				,      keep_in_memory=A   ).read()
	_check_text_dataset(A				,      A   )




@pytest.mark.parametrize(
    """features"""				,      [
        None,
        {"""text""": """string"""},
        {"""text""": """int32"""},
        {"""text""": """float32"""},
    ]				,      )
def    A_(			A				,      A				,      A   ):
	UpperCAmelCase_								=     tmp_path / """cache"""
	UpperCAmelCase_								=     {"""text""": """string"""}
	UpperCAmelCase_								=     features.copy() if features else default_expected_features
	UpperCAmelCase_								=     (
	    Features({feature: Value(A   ) for feature, dtype in features.items()}   ) if features is not None else None
	)
	UpperCAmelCase_								=     TextDatasetReader(A				,      features=A				,      cache_dir=A   ).read()
	_check_text_dataset(A				,      A   )




@pytest.mark.parametrize("""split"""				,      [None, NamedSplit("""train"""   ), """train""", """test"""]   )
def    A_(			A				,      A				,      A   ):
	UpperCAmelCase_								=     tmp_path / """cache"""
	UpperCAmelCase_								=     {"""text""": """string"""}
	UpperCAmelCase_								=     TextDatasetReader(A				,      cache_dir=A				,      split=A   ).read()
	_check_text_dataset(A				,      A   )
	assert dataset.split == split if split else "train"




@pytest.mark.parametrize("""path_type"""				,      [str, list]   )
def    A_(			A				,      A				,      A   ):
	if issubclass(A				,      A   ):
		UpperCAmelCase_								=     text_path
	elif issubclass(A				,      A   ):
		UpperCAmelCase_								=     [text_path]
	UpperCAmelCase_								=     tmp_path / """cache"""
	UpperCAmelCase_								=     {"""text""": """string"""}
	UpperCAmelCase_								=     TextDatasetReader(A				,      cache_dir=A   ).read()
	_check_text_dataset(A				,      A   )




def    A_(			A				,      A				,      A=("train",)   ):
	assert isinstance(A				,      A   )
	for split in splits:
		UpperCAmelCase_								=     dataset_dict[split]
		assert dataset.num_rows == 4
		assert dataset.num_columns == 1
		assert dataset.column_names == ["text"]
		for feature, expected_dtype in expected_features.items():
			assert dataset.features[feature].dtype == expected_dtype




@pytest.mark.parametrize("""keep_in_memory"""				,      [False, True]   )
def    A_(			A				,      A				,      A   ):
	UpperCAmelCase_								=     tmp_path / """cache"""
	UpperCAmelCase_								=     {"""text""": """string"""}
	with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
		UpperCAmelCase_								=     TextDatasetReader({"""train""": text_path}				,      cache_dir=A				,      keep_in_memory=A   ).read()
	_check_text_datasetdict(A				,      A   )




@pytest.mark.parametrize(
    """features"""				,      [
        None,
        {"""text""": """string"""},
        {"""text""": """int32"""},
        {"""text""": """float32"""},
    ]				,      )
def    A_(			A				,      A				,      A   ):
	UpperCAmelCase_								=     tmp_path / """cache"""
	# CSV file loses col_1 string dtype information: default now is "int64" instead of "string"
	UpperCAmelCase_								=     {"""text""": """string"""}
	UpperCAmelCase_								=     features.copy() if features else default_expected_features
	UpperCAmelCase_								=     (
	    Features({feature: Value(A   ) for feature, dtype in features.items()}   ) if features is not None else None
	)
	UpperCAmelCase_								=     TextDatasetReader({"""train""": text_path}				,      features=A				,      cache_dir=A   ).read()
	_check_text_datasetdict(A				,      A   )




@pytest.mark.parametrize("""split"""				,      [None, NamedSplit("""train"""   ), """train""", """test"""]   )
def    A_(			A				,      A				,      A   ):
	if split:
		UpperCAmelCase_								=     {split: text_path}
	else:
		UpperCAmelCase_								=     """train"""
		UpperCAmelCase_								=     {"""train""": text_path, """test""": text_path}
	UpperCAmelCase_								=     tmp_path / """cache"""
	UpperCAmelCase_								=     {"""text""": """string"""}
	UpperCAmelCase_								=     TextDatasetReader(A				,      cache_dir=A   ).read()
	_check_text_datasetdict(A				,      A				,      splits=list(path.keys()   )   )
	assert all(dataset[split].split == split for split in path.keys()   )


