
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_ (							snake_case							:   Dict ,      snake_case							:   List[str] )      ->    List[str]:



						'''simple docstring'''

						assert isinstance(snake_case ,      snake_case )
						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_ (							snake_case							:   List[Any] ,      snake_case							:   Tuple ,      snake_case							:   Union[str, Any] )      ->    Union[str, Any]:



						'''simple docstring'''

						__UpperCamelCase       =			tmp_path / '''cache'''
						__UpperCamelCase       =			{'''text''': '''string'''}
						with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
												__UpperCamelCase       =			TextDatasetReader(snake_case ,      cache_dir=snake_case ,      keep_in_memory=snake_case ).read()
						_check_text_dataset(snake_case ,      snake_case )




@pytest.mark.parametrize(
    '''features''' ,      [
        None,
        {'''text''': '''string'''},
        {'''text''': '''int32'''},
        {'''text''': '''float32'''},
    ] ,      )
def 	A_ (							snake_case							:   str ,      snake_case							:   List[Any] ,      snake_case							:   Dict )      ->    Any:



						'''simple docstring'''

						__UpperCamelCase       =			tmp_path / '''cache'''
						__UpperCamelCase       =			{'''text''': '''string'''}
						__UpperCamelCase       =			features.copy() if features else default_expected_features
						__UpperCamelCase       =			(
						    Features({feature: Value(snake_case ) for feature, dtype in features.items()} ) if features is not None else None
						)
						__UpperCamelCase       =			TextDatasetReader(snake_case ,      features=snake_case ,      cache_dir=snake_case ).read()
						_check_text_dataset(snake_case ,      snake_case )




@pytest.mark.parametrize('''split''' ,      [None, NamedSplit('''train''' ), '''train''', '''test'''] )
def 	A_ (							snake_case							:   Dict ,      snake_case							:   Any ,      snake_case							:   Any )      ->    str:



						'''simple docstring'''

						__UpperCamelCase       =			tmp_path / '''cache'''
						__UpperCamelCase       =			{'''text''': '''string'''}
						__UpperCamelCase       =			TextDatasetReader(snake_case ,      cache_dir=snake_case ,      split=snake_case ).read()
						_check_text_dataset(snake_case ,      snake_case )
						assert dataset.split == split if split else "train"




@pytest.mark.parametrize('''path_type''' ,      [str, list] )
def 	A_ (							snake_case							:   Optional[int] ,      snake_case							:   Union[str, Any] ,      snake_case							:   List[str] )      ->    List[Any]:



						'''simple docstring'''

						if issubclass(snake_case ,      snake_case ):
												__UpperCamelCase       =			text_path
						elif issubclass(snake_case ,      snake_case ):
												__UpperCamelCase       =			[text_path]
						__UpperCamelCase       =			tmp_path / '''cache'''
						__UpperCamelCase       =			{'''text''': '''string'''}
						__UpperCamelCase       =			TextDatasetReader(snake_case ,      cache_dir=snake_case ).read()
						_check_text_dataset(snake_case ,      snake_case )




def 	A_ (							snake_case							:   str ,      snake_case							:   Any ,      snake_case							:   Dict=("train",) )      ->    Any:



						'''simple docstring'''

						assert isinstance(snake_case ,      snake_case )
						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_ (							snake_case							:   List[str] ,      snake_case							:   Any ,      snake_case							:   Optional[int] )      ->    Union[str, Any]:



						'''simple docstring'''

						__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=snake_case ,      keep_in_memory=snake_case ).read()
						_check_text_datasetdict(snake_case ,      snake_case )




@pytest.mark.parametrize(
    '''features''' ,      [
        None,
        {'''text''': '''string'''},
        {'''text''': '''int32'''},
        {'''text''': '''float32'''},
    ] ,      )
def 	A_ (							snake_case							:   Any ,      snake_case							:   str ,      snake_case							:   Optional[Any] )      ->    List[str]:



						'''simple docstring'''

						__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(snake_case ) for feature, dtype in features.items()} ) if features is not None else None
						)
						__UpperCamelCase       =			TextDatasetReader({'''train''': text_path} ,      features=snake_case ,      cache_dir=snake_case ).read()
						_check_text_datasetdict(snake_case ,      snake_case )




@pytest.mark.parametrize('''split''' ,      [None, NamedSplit('''train''' ), '''train''', '''test'''] )
def 	A_ (							snake_case							:   Tuple ,      snake_case							:   Tuple ,      snake_case							:   str )      ->    List[str]:



						'''simple docstring'''

						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(snake_case ,      cache_dir=snake_case ).read()
						_check_text_datasetdict(snake_case ,      snake_case ,      splits=list(path.keys() ) )
						assert all(dataset[split].split == split for split in path.keys() )





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






@add_end_docstrings(SCREAMING_SNAKE_CASE_    )
class        SCREAMING_SNAKE_CASE__    (							SCREAMING_SNAKE_CASE_    ):

							"""simple docstring"""






							def __init__(  self     ,	**SCREAMING_SNAKE_CASE_			)->   Tuple:





													'''simple docstring'''






													super().__init__(**SCREAMING_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     ,	SCREAMING_SNAKE_CASE_     ,	**SCREAMING_SNAKE_CASE_			)->   str:





													'''simple docstring'''






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



							def     A__		(  self     ,	**SCREAMING_SNAKE_CASE_			)->   Tuple:





													'''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     A__		(  self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_=None     ,	SCREAMING_SNAKE_CASE_="This is a photo of {}."			)->   Optional[int]:





													'''simple docstring'''






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



							def     A__		(  self     ,	SCREAMING_SNAKE_CASE_			)->   Dict:





													'''simple docstring'''






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

													__UpperCamelCase       =			self.model(**SCREAMING_SNAKE_CASE_     ,	**SCREAMING_SNAKE_CASE_			)

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



							def     A__		(  self     ,	SCREAMING_SNAKE_CASE_			)->   int:





													'''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(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_			):
																									__UpperCamelCase       =			[scores]
													elif self.framework == "tf":
																			__UpperCamelCase       =			stable_softmax(SCREAMING_SNAKE_CASE_     ,	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(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_			)     ,	key=lambda SCREAMING_SNAKE_CASE_			: -x[0]			)
													]
													return result




