


'''simple docstring'''
from typing import Any, Dict, List, Union

from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends
from .base import PIPELINE_INIT_ARGS, ChunkPipeline


if is_vision_available():
		from PIL import Image

		from ..image_utils import load_image

if is_torch_available():
		import torch

		from transformers.modeling_outputs import BaseModelOutput

		from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING

__snake_case							      =     logging.get_logger(__name__)
@add_end_docstrings(A__					)
class    lowercase	(							A__					):

		"""simple docstring"""

		def __init__(		self    ,   **UpperCamelCase_							):

							'''simple docstring'''


							super().__init__(**UpperCamelCase_							)

							if self.framework == "tf":
												raise ValueError(F'''The {self.__class__} is only available in PyTorch.'''							)

							requires_backends(self    ,   '''vision'''							)
							self.check_model_type(UpperCamelCase_							)




		def __call__(		self    ,   UpperCamelCase_    ,   UpperCamelCase_ = None    ,   **UpperCamelCase_    ,   ):

							'''simple docstring'''


							if "text_queries" in kwargs:
												UpperCamelCase__   :str												= kwargs.pop('''text_queries'''							)

							if isinstance(UpperCamelCase_    ,   (str, Image.Image)							):
												UpperCamelCase__   :List[Any]												= {'''image''': image, '''candidate_labels''': candidate_labels}
							else:
												UpperCamelCase__   :Any												= image
							UpperCamelCase__   :Optional[int]												= super().__call__(UpperCamelCase_    ,   **UpperCamelCase_							)
							return results




		def     lowerCAmelCase__				(		self    ,   **UpperCamelCase_							):

							'''simple docstring'''


							UpperCamelCase__   :Any												= {}
							if "threshold" in kwargs:
												UpperCamelCase__   :List[Any]												= kwargs['''threshold''']
							if "top_k" in kwargs:
												UpperCamelCase__   :Optional[Any]												= kwargs['''top_k''']
							return {}, {}, postprocess_params




		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_							):

							'''simple docstring'''


							UpperCamelCase__   :str												= load_image(inputs['''image''']							)
							UpperCamelCase__   :Dict												= inputs['''candidate_labels''']
							if isinstance(UpperCamelCase_    ,   UpperCamelCase_							):
												UpperCamelCase__   :Optional[Any]												= candidate_labels.split(''','''							)

							UpperCamelCase__   :Union[str, Any]												= torch.tensor([[image.height, image.width]]    ,   dtype=torch.intaa							)
							for i, candidate_label in enumerate(UpperCamelCase_							):
												UpperCamelCase__   :List[str]												= self.tokenizer(UpperCamelCase_    ,   return_tensors=self.framework							)
												UpperCamelCase__   :Optional[int]												= self.image_processor(UpperCamelCase_    ,   return_tensors=self.framework							)
												yield {
												    "is_last": i == len(UpperCamelCase_							) - 1,
												    "target_size": target_size,
												    "candidate_label": candidate_label,
												    **text_inputs,
												    **image_features,
												}




		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_							):

							'''simple docstring'''


							UpperCamelCase__   :int												= model_inputs.pop('''target_size'''							)
							UpperCamelCase__   :Optional[int]												= model_inputs.pop('''candidate_label'''							)
							UpperCamelCase__   :List[Any]												= model_inputs.pop('''is_last'''							)

							UpperCamelCase__   :str												= self.model(**UpperCamelCase_							)

							UpperCamelCase__   :str												= {'''target_size''': target_size, '''candidate_label''': candidate_label, '''is_last''': is_last, **outputs}
							return model_outputs




		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_    ,   UpperCamelCase_=0.1    ,   UpperCamelCase_=None							):

							'''simple docstring'''


							UpperCamelCase__   :str												= []
							for model_output in model_outputs:
												UpperCamelCase__   :Optional[int]												= model_output['''candidate_label''']
												UpperCamelCase__   :Union[str, Any]												= BaseModelOutput(UpperCamelCase_							)
												UpperCamelCase__   :Tuple												= self.image_processor.post_process_object_detection(
												    outputs=UpperCamelCase_    ,   threshold=UpperCamelCase_    ,   target_sizes=model_output['''target_size''']							)[0]

												for index in outputs["scores"].nonzero():
																	UpperCamelCase__   :Dict												= outputs['''scores'''][index].item()
																	UpperCamelCase__   :int												= self._get_bounding_box(outputs['''boxes'''][index][0]							)

																	UpperCamelCase__   :Optional[int]												= {'''score''': score, '''label''': label, '''box''': box}
																	results.append(UpperCamelCase_							)

							UpperCamelCase__   :Optional[int]												= sorted(UpperCamelCase_    ,   key=lambda UpperCamelCase_							: x["score"]    ,   reverse=UpperCamelCase_							)
							if top_k:
												UpperCamelCase__   :Tuple												= results[:top_k]

							return results




		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_							):

							'''simple docstring'''


							if self.framework != "pt":
												raise ValueError('''The ZeroShotObjectDetectionPipeline is only available in PyTorch.'''							)
							UpperCamelCase__					,				UpperCamelCase__					,				UpperCamelCase__					,				UpperCamelCase__   :List[str]												= box.int().tolist()
							UpperCamelCase__   :Union[str, Any]												= {
							    '''xmin''': xmin,
							    '''ymin''': ymin,
							    '''xmax''': xmax,
							    '''ymax''': ymax,
							}
							return bbox



'''simple docstring'''
import io
import json

import fsspec
import pytest

from datasets import Dataset, DatasetDict, Features, NamedSplit, Value
from datasets.io.json import JsonDatasetReader, JsonDatasetWriter

from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases


def 			a      (			__a ,					__a   )  ->	Optional[int]:



					'''simple docstring'''






					assert isinstance(__a ,					__a   )
					assert dataset.num_rows == 4
					assert dataset.num_columns == 3
					assert dataset.column_names == ["col_1", "col_2", "col_3"]
					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   )  ->	Optional[Any]:



					'''simple docstring'''






					UpperCamelCase__   :Union[str, Any]												= tmp_path / '''cache'''
					UpperCamelCase__   :Dict												= {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
					with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
										UpperCamelCase__   :Tuple												= JsonDatasetReader(__a ,					cache_dir=__a ,					keep_in_memory=__a   ).read()
					_check_json_dataset(__a ,					__a   )


@pytest.mark.parametrize(
    '''features''' ,					[
        None,
        {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''},
        {'''col_1''': '''string''', '''col_2''': '''string''', '''col_3''': '''string'''},
        {'''col_1''': '''int32''', '''col_2''': '''int32''', '''col_3''': '''int32'''},
        {'''col_1''': '''float32''', '''col_2''': '''float32''', '''col_3''': '''float32'''},
    ] ,					)
def 			a      (			__a ,					__a ,					__a   )  ->	Any:



					'''simple docstring'''






					UpperCamelCase__   :Union[str, Any]												= tmp_path / '''cache'''
					UpperCamelCase__   :Optional[Any]												= {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
					UpperCamelCase__   :Optional[Any]												= features.copy() if features else default_expected_features
					UpperCamelCase__   :Tuple												= (
					    Features({feature: Value(__a   ) for feature, dtype in features.items()}   ) if features is not None else None
					)
					UpperCamelCase__   :int												= JsonDatasetReader(__a ,					features=__a ,					cache_dir=__a   ).read()
					_check_json_dataset(__a ,					__a   )


@pytest.mark.parametrize(
    '''features''' ,					[
        None,
        {'''col_3''': '''float64''', '''col_1''': '''string''', '''col_2''': '''int64'''},
    ] ,					)
def 			a      (			__a ,					__a ,					__a   )  ->	Tuple:



					'''simple docstring'''






					UpperCamelCase__   :int												= tmp_path / '''cache'''
					UpperCamelCase__   :str												= {'''col_3''': '''float64''', '''col_1''': '''string''', '''col_2''': '''int64'''}
					UpperCamelCase__   :Any												= features.copy() if features else default_expected_features
					UpperCamelCase__   :Union[str, Any]												= (
					    Features({feature: Value(__a   ) for feature, dtype in features.items()}   ) if features is not None else None
					)
					UpperCamelCase__   :Any												= JsonDatasetReader(__a ,					features=__a ,					cache_dir=__a   ).read()
					assert isinstance(__a ,					__a   )
					assert dataset.num_rows == 2
					assert dataset.num_columns == 3
					assert dataset.column_names == ["col_3", "col_1", "col_2"]
					for feature, expected_dtype in expected_features.items():
										assert dataset.features[feature].dtype == expected_dtype


def 			a      (			__a ,					__a   )  ->	List[Any]:



					'''simple docstring'''






					UpperCamelCase__   :Any												= {'''col_2''': '''int64''', '''col_3''': '''float64''', '''col_1''': '''string'''}
					UpperCamelCase__   :int												= features.copy()
					UpperCamelCase__   :List[Any]												= (
					    Features({feature: Value(__a   ) for feature, dtype in features.items()}   ) if features is not None else None
					)
					UpperCamelCase__   :Optional[int]												= tmp_path / '''cache'''
					UpperCamelCase__   :Dict												= JsonDatasetReader(__a ,					features=__a ,					cache_dir=__a   ).read()
					assert isinstance(__a ,					__a   )
					assert dataset.num_rows == 2
					assert dataset.num_columns == 3
					assert dataset.column_names == ["col_2", "col_3", "col_1"]
					for feature, expected_dtype in expected_features.items():
										assert dataset.features[feature].dtype == expected_dtype


@pytest.mark.parametrize('''split''' ,					[None, NamedSplit('''train'''   ), '''train''', '''test''']   )
def 			a      (			__a ,					__a ,					__a   )  ->	List[Any]:



					'''simple docstring'''






					UpperCamelCase__   :Union[str, Any]												= tmp_path / '''cache'''
					UpperCamelCase__   :Optional[Any]												= {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
					UpperCamelCase__   :List[Any]												= JsonDatasetReader(__a ,					cache_dir=__a ,					split=__a   ).read()
					_check_json_dataset(__a ,					__a   )
					assert dataset.split == split if split else "train"


@pytest.mark.parametrize('''path_type''' ,					[str, list]   )
def 			a      (			__a ,					__a ,					__a   )  ->	Any:



					'''simple docstring'''






					if issubclass(__a ,					__a   ):
										UpperCamelCase__   :Union[str, Any]												= jsonl_path
					elif issubclass(__a ,					__a   ):
										UpperCamelCase__   :int												= [jsonl_path]
					UpperCamelCase__   :Dict												= tmp_path / '''cache'''
					UpperCamelCase__   :Any												= {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
					UpperCamelCase__   :List[str]												= JsonDatasetReader(__a ,					cache_dir=__a   ).read()
					_check_json_dataset(__a ,					__a   )


def 			a      (			__a ,					__a ,					__a=("train",)   )  ->	Optional[Any]:



					'''simple docstring'''






					assert isinstance(__a ,					__a   )
					for split in splits:
										UpperCamelCase__   :Optional[int]												= dataset_dict[split]
										assert dataset.num_rows == 4
										assert dataset.num_columns == 3
										assert dataset.column_names == ["col_1", "col_2", "col_3"]
										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   )  ->	List[str]:



					'''simple docstring'''






					UpperCamelCase__   :List[str]												= tmp_path / '''cache'''
					UpperCamelCase__   :Dict												= {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
					with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
										UpperCamelCase__   :str												= JsonDatasetReader({'''train''': jsonl_path} ,					cache_dir=__a ,					keep_in_memory=__a   ).read()
					_check_json_datasetdict(__a ,					__a   )


@pytest.mark.parametrize(
    '''features''' ,					[
        None,
        {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''},
        {'''col_1''': '''string''', '''col_2''': '''string''', '''col_3''': '''string'''},
        {'''col_1''': '''int32''', '''col_2''': '''int32''', '''col_3''': '''int32'''},
        {'''col_1''': '''float32''', '''col_2''': '''float32''', '''col_3''': '''float32'''},
    ] ,					)
def 			a      (			__a ,					__a ,					__a   )  ->	int:



					'''simple docstring'''






					UpperCamelCase__   :Tuple												= tmp_path / '''cache'''
					UpperCamelCase__   :Any												= {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
					UpperCamelCase__   :Optional[int]												= features.copy() if features else default_expected_features
					UpperCamelCase__   :str												= (
					    Features({feature: Value(__a   ) for feature, dtype in features.items()}   ) if features is not None else None
					)
					UpperCamelCase__   :Dict												= JsonDatasetReader({'''train''': jsonl_path} ,					features=__a ,					cache_dir=__a   ).read()
					_check_json_datasetdict(__a ,					__a   )


@pytest.mark.parametrize('''split''' ,					[None, NamedSplit('''train'''   ), '''train''', '''test''']   )
def 			a      (			__a ,					__a ,					__a   )  ->	str:



					'''simple docstring'''






					if split:
										UpperCamelCase__   :List[str]												= {split: jsonl_path}
					else:
										UpperCamelCase__   :int												= '''train'''
										UpperCamelCase__   :int												= {'''train''': jsonl_path, '''test''': jsonl_path}
					UpperCamelCase__   :Any												= tmp_path / '''cache'''
					UpperCamelCase__   :Union[str, Any]												= {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
					UpperCamelCase__   :Any												= JsonDatasetReader(__a ,					cache_dir=__a   ).read()
					_check_json_datasetdict(__a ,					__a ,					splits=list(path.keys()   )   )
					assert all(dataset[split].split == split for split in path.keys()   )


def 			a      (			__a   )  ->	Union[str, Any]:



					'''simple docstring'''






					return json.load(__a   )


def 			a      (			__a   )  ->	int:



					'''simple docstring'''






					return [json.loads(__a   ) for line in buffer]







class    lowercase	:

		"""simple docstring"""

		@pytest.mark.parametrize('''lines, load_json_function'''    ,   [(True, load_json_lines), (False, load_json)]							)
		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_							):

							'''simple docstring'''


							with io.BytesIO() as buffer:
												JsonDatasetWriter(UpperCamelCase_    ,   UpperCamelCase_    ,   lines=UpperCamelCase_							).write()
												buffer.seek(0							)
												UpperCamelCase__   :List[Any]												= load_json_function(UpperCamelCase_							)
							assert isinstance(UpperCamelCase_    ,   UpperCamelCase_							)
							assert isinstance(exported_content[0]    ,   UpperCamelCase_							)
							assert len(UpperCamelCase_							) == 10




		@pytest.mark.parametrize(
		    '''orient, container, keys, len_at'''    ,   [
		        ('''records''', list, {'''tokens''', '''labels''', '''answers''', '''id'''}, None),
		        ('''split''', dict, {'''columns''', '''data'''}, '''data'''),
		        ('''index''', dict, set('''0123456789'''							), None),
		        ('''columns''', dict, {'''tokens''', '''labels''', '''answers''', '''id'''}, '''tokens'''),
		        ('''values''', list, None, None),
		        ('''table''', dict, {'''schema''', '''data'''}, '''data'''),
		    ]    ,   )
		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_							):

							'''simple docstring'''


							with io.BytesIO() as buffer:
												JsonDatasetWriter(UpperCamelCase_    ,   UpperCamelCase_    ,   lines=UpperCamelCase_    ,   orient=UpperCamelCase_							).write()
												buffer.seek(0							)
												UpperCamelCase__   :Optional[int]												= load_json(UpperCamelCase_							)
							assert isinstance(UpperCamelCase_    ,   UpperCamelCase_							)
							if keys:
												if container is dict:
																	assert exported_content.keys() == keys
												else:
																	assert exported_content[0].keys() == keys
							else:
												assert not hasattr(UpperCamelCase_    ,   '''keys'''							) and not hasattr(exported_content[0]    ,   '''keys'''							)
							if len_at:
												assert len(exported_content[len_at]							) == 10
							else:
												assert len(UpperCamelCase_							) == 10




		@pytest.mark.parametrize('''lines, load_json_function'''    ,   [(True, load_json_lines), (False, load_json)]							)
		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_							):

							'''simple docstring'''


							with io.BytesIO() as buffer:
												JsonDatasetWriter(UpperCamelCase_    ,   UpperCamelCase_    ,   lines=UpperCamelCase_    ,   num_proc=2							).write()
												buffer.seek(0							)
												UpperCamelCase__   :Union[str, Any]												= load_json_function(UpperCamelCase_							)
							assert isinstance(UpperCamelCase_    ,   UpperCamelCase_							)
							assert isinstance(exported_content[0]    ,   UpperCamelCase_							)
							assert len(UpperCamelCase_							) == 10




		@pytest.mark.parametrize(
		    '''orient, container, keys, len_at'''    ,   [
		        ('''records''', list, {'''tokens''', '''labels''', '''answers''', '''id'''}, None),
		        ('''split''', dict, {'''columns''', '''data'''}, '''data'''),
		        ('''index''', dict, set('''0123456789'''							), None),
		        ('''columns''', dict, {'''tokens''', '''labels''', '''answers''', '''id'''}, '''tokens'''),
		        ('''values''', list, None, None),
		        ('''table''', dict, {'''schema''', '''data'''}, '''data'''),
		    ]    ,   )
		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_							):

							'''simple docstring'''


							with io.BytesIO() as buffer:
												JsonDatasetWriter(UpperCamelCase_    ,   UpperCamelCase_    ,   lines=UpperCamelCase_    ,   orient=UpperCamelCase_    ,   num_proc=2							).write()
												buffer.seek(0							)
												UpperCamelCase__   :int												= load_json(UpperCamelCase_							)
							assert isinstance(UpperCamelCase_    ,   UpperCamelCase_							)
							if keys:
												if container is dict:
																	assert exported_content.keys() == keys
												else:
																	assert exported_content[0].keys() == keys
							else:
												assert not hasattr(UpperCamelCase_    ,   '''keys'''							) and not hasattr(exported_content[0]    ,   '''keys'''							)
							if len_at:
												assert len(exported_content[len_at]							) == 10
							else:
												assert len(UpperCamelCase_							) == 10




		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_							):

							'''simple docstring'''


							with pytest.raises(UpperCamelCase_							):
												with io.BytesIO() as buffer:
																	JsonDatasetWriter(UpperCamelCase_    ,   UpperCamelCase_    ,   num_proc=0							)




		@pytest.mark.parametrize('''compression, extension'''    ,   [('''gzip''', '''gz'''), ('''bz2''', '''bz2'''), ('''xz''', '''xz''')]							)
		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_							):

							'''simple docstring'''


							UpperCamelCase__   :Tuple												= tmp_path_factory.mktemp('''data'''							) / F'''test.json.{extension}'''
							UpperCamelCase__   :Union[str, Any]												= str(shared_datadir / F'''test_file.json.{extension}'''							)
							JsonDatasetWriter(UpperCamelCase_    ,   UpperCamelCase_    ,   compression=UpperCamelCase_							).write()

							with fsspec.open(UpperCamelCase_    ,   '''rb'''    ,   compression='''infer'''							) as f:
												UpperCamelCase__   :Dict												= f.read()
							with fsspec.open(UpperCamelCase_    ,   '''rb'''    ,   compression='''infer'''							) as f:
												UpperCamelCase__   :int												= f.read()
							assert exported_content == original_content