
'''simple docstring'''

import itertools
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Union

import pandas as pd
import pyarrow as pa

import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast
from datasets.utils.py_utils import Literal


_UpperCAmelCase :   List[Any]			    =	datasets.utils.logging.get_logger(__name__)

_UpperCAmelCase :   Tuple			    =	["names", "prefix"]
_UpperCAmelCase :   List[Any]			    =	["warn_bad_lines", "error_bad_lines", "mangle_dupe_cols"]
_UpperCAmelCase :   Optional[int]			    =	["encoding_errors", "on_bad_lines"]
_UpperCAmelCase :   Dict			    =	["date_format"]

@dataclass
class       UpperCAmelCase					(       datasets.BuilderConfig			):





		"""simple docstring"""





		A__	: str    =     ','
		A__	: Union[str, Any]    =     None
		A__	: int    =     'infer'
		A__	: Any    =     None
		A__	: Tuple    =     None
		A__	: Optional[Any]    =     None
		A__	: Dict    =     None
		A__	: List[str]    =     None
		A__	: Optional[int]    =     True
		A__	: int    =     None
		A__	: Optional[int]    =     None
		A__	: Dict    =     None
		A__	: Optional[Any]    =     None
		A__	: Optional[int]    =     False
		A__	: Optional[int]    =     None
		A__	: Dict    =     None
		A__	: List[Any]    =     None
		A__	: Any    =     True
		A__	: Tuple    =     True
		A__	: str    =     False
		A__	: List[Any]    =     True
		A__	: str    =     None
		A__	: str    =     '.'
		A__	: Optional[Any]    =     None
		A__	: int    =     '"'
		A__	: Optional[Any]    =     0
		A__	: Optional[int]    =     None
		A__	: Any    =     None
		A__	: Any    =     None
		A__	: Tuple    =     None
		A__	: Union[str, Any]    =     True
		A__	: Optional[Any]    =     True
		A__	: Dict    =     0
		A__	: Any    =     True
		A__	: Union[str, Any]    =     False
		A__	: str    =     None
		A__	: str    =     10000
		A__	: Any    =     None
		A__	: str    =     'strict'
		A__	: Any    =     'error'
		A__	: Any    =     None
		def _lowercase	(     self  )					->     Optional[int]:
				if self.delimiter is not None:
						_UpperCamelCase							:			List[Any]     =   self.delimiter
				if self.column_names is not None:
						_UpperCamelCase							:			List[str]     =   self.column_names




		@property
		def _lowercase	(     self  )					->     List[str]:
				_UpperCamelCase							:			Tuple     =   {
				    '''sep''': self.sep,
				    '''header''': self.header,
				    '''names''': self.names,
				    '''index_col''': self.index_col,
				    '''usecols''': self.usecols,
				    '''prefix''': self.prefix,
				    '''mangle_dupe_cols''': self.mangle_dupe_cols,
				    '''engine''': self.engine,
				    '''converters''': self.converters,
				    '''true_values''': self.true_values,
				    '''false_values''': self.false_values,
				    '''skipinitialspace''': self.skipinitialspace,
				    '''skiprows''': self.skiprows,
				    '''nrows''': self.nrows,
				    '''na_values''': self.na_values,
				    '''keep_default_na''': self.keep_default_na,
				    '''na_filter''': self.na_filter,
				    '''verbose''': self.verbose,
				    '''skip_blank_lines''': self.skip_blank_lines,
				    '''thousands''': self.thousands,
				    '''decimal''': self.decimal,
				    '''lineterminator''': self.lineterminator,
				    '''quotechar''': self.quotechar,
				    '''quoting''': self.quoting,
				    '''escapechar''': self.escapechar,
				    '''comment''': self.comment,
				    '''encoding''': self.encoding,
				    '''dialect''': self.dialect,
				    '''error_bad_lines''': self.error_bad_lines,
				    '''warn_bad_lines''': self.warn_bad_lines,
				    '''skipfooter''': self.skipfooter,
				    '''doublequote''': self.doublequote,
				    '''memory_map''': self.memory_map,
				    '''float_precision''': self.float_precision,
				    '''chunksize''': self.chunksize,
				    '''encoding_errors''': self.encoding_errors,
				    '''on_bad_lines''': self.on_bad_lines,
				    '''date_format''': self.date_format,
				}

				# some kwargs must not be passed if they don't have a default value
				# some others are deprecated and we can also not pass them if they are the default value
				for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS:
						if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig()	,       _lowercase  ):
								del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 2.0 new arguments
				if not (datasets.config.PANDAS_VERSION.major >= 2):
						for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS:
								del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 1.3 new arguments
				if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3):
						for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS:
								del pd_read_csv_kwargs[pd_read_csv_parameter]

				return pd_read_csv_kwargs







class       UpperCAmelCase					(       datasets.ArrowBasedBuilder			):





		"""simple docstring"""





		A__	: Dict    =     CsvConfig
		def _lowercase	(     self  )					->     str:
				return datasets.DatasetInfo(features=self.config.features  )
		def _lowercase	(     self	,       _snake_case  )					->     Optional[int]:
				if not self.config.data_files:
						raise ValueError(F'''At least one data file must be specified, but got data_files={self.config.data_files}'''  )
				_UpperCamelCase							:			Tuple     =   dl_manager.download_and_extract(self.config.data_files  )
				if isinstance(_lowercase	,       (str, list, tuple)  ):
						_UpperCamelCase							:			Optional[int]     =   data_files
						if isinstance(_lowercase	,       _lowercase  ):
								_UpperCamelCase							:			List[Any]     =   [files]
						_UpperCamelCase							:			Optional[int]     =   [dl_manager.iter_files(_lowercase  ) for file in files]
						return [datasets.SplitGenerator(name=datasets.Split.TRAIN	,       gen_kwargs={'''files''': files}  )]
				_UpperCamelCase							:			str     =   []
				for split_name, files in data_files.items():
						if isinstance(_lowercase	,       _lowercase  ):
								_UpperCamelCase							:			Tuple     =   [files]
						_UpperCamelCase							:			Tuple     =   [dl_manager.iter_files(_lowercase  ) for file in files]
						splits.append(datasets.SplitGenerator(name=_lowercase	,       gen_kwargs={'''files''': files}  )  )
				return splits
		def _lowercase	(     self	,       _snake_case  )					->     pa.Table:
				if self.config.features is not None:
						_UpperCamelCase							:			int     =   self.config.features.arrow_schema
						if all(not require_storage_cast(_lowercase  ) for feature in self.config.features.values()  ):
								# cheaper cast
								_UpperCamelCase							:			str     =   pa.Table.from_arrays([pa_table[field.name] for field in schema]	,       schema=_lowercase  )
						else:
								# more expensive cast; allows str <-> int/float or str to Audio for example
								_UpperCamelCase							:			str     =   table_cast(_lowercase	,       _lowercase  )
				return pa_table




		def _lowercase	(     self	,       _snake_case  )					->     Optional[Any]:
				_UpperCamelCase							:			Any     =   self.config.features.arrow_schema if self.config.features else None
				# dtype allows reading an int column as str
				_UpperCamelCase							:			Dict     =   (
				    {
				        name: dtype.to_pandas_dtype() if not require_storage_cast(_lowercase  ) else object
				        for name, dtype, feature in zip(schema.names	,       schema.types	,       self.config.features.values()  )
				    }
				    if schema is not None
				    else None
				)
				for file_idx, file in enumerate(itertools.chain.from_iterable(_lowercase  )  ):
						_UpperCamelCase							:			Tuple     =   pd.read_csv(_lowercase	,       iterator=_lowercase	,       dtype=_lowercase	,       **self.config.pd_read_csv_kwargs  )
						try:
								for batch_idx, df in enumerate(_lowercase  ):
										_UpperCamelCase							:			Union[str, Any]     =   pa.Table.from_pandas(_lowercase  )
										# Uncomment for debugging (will print the Arrow table size and elements)
										# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
										# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
										yield (file_idx, batch_idx), self._cast_table(_lowercase  )
						except ValueError as e:
								logger.error(F'''Failed to read file \'{file}\' with error {type(_lowercase  )}: {e}'''  )
								raise








'''simple docstring'''

import unittest

from transformers import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, is_vision_available, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
							from PIL import Image
else:






							class    snake_case     :






											"""simple docstring"""



											@staticmethod
											def   a__					(    *_lowercase,     **_lowercase       )     ->							Tuple:
																		pass






@is_pipeline_test
@require_vision
@require_torch
class    snake_case     (      unittest.TestCase		):






				"""simple docstring"""
				_a    	=     MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING



				def   a__					(    self,     _lowercase,     _lowercase,     _lowercase       )     ->							Tuple:
											SCREAMING_SNAKE_CASE_				=				pipeline(
											    'zero-shot-object-detection',     model='hf-internal-testing/tiny-random-owlvit-object-detection'       )

											SCREAMING_SNAKE_CASE_				=				[
											    {
											        'image': './tests/fixtures/tests_samples/COCO/000000039769.png',
											        'candidate_labels': ['cat', 'remote', 'couch'],
											    }
											]
											return object_detector, examples



				def   a__					(    self,     _lowercase,     _lowercase       )     ->							str:
											SCREAMING_SNAKE_CASE_				=				object_detector(examples[0],     threshold=0.0       )

											SCREAMING_SNAKE_CASE_				=				len(_lowercase       )
											self.assertGreater(_lowercase,     0       )
											self.assertEqual(
											    _lowercase,     [
											        {
											            'score': ANY(_lowercase       ),
											            'label': ANY(_lowercase       ),
											            'box': {'xmin': ANY(_lowercase       ), 'ymin': ANY(_lowercase       ), 'xmax': ANY(_lowercase       ), 'ymax': ANY(_lowercase       )},
											        }
											        for i in range(_lowercase       )
											    ],     )



				@require_tf
				@unittest.skip('Zero Shot Object Detection not implemented in TF'       )
				def   a__					(    self       )     ->							Union[str, Any]:
											pass



				@require_torch
				def   a__					(    self       )     ->							str:
											SCREAMING_SNAKE_CASE_				=				pipeline(
											    'zero-shot-object-detection',     model='hf-internal-testing/tiny-random-owlvit-object-detection'       )

											SCREAMING_SNAKE_CASE_				=				object_detector(
											    './tests/fixtures/tests_samples/COCO/000000039769.png',     candidate_labels=['cat', 'remote', 'couch'],     threshold=0.64,     )

											self.assertEqual(
											    nested_simplify(_lowercase,     decimals=4       ),     [
											        {'score': 0.7_235, 'label': 'cat', 'box': {'xmin': 204, 'ymin': 167, 'xmax': 232, 'ymax': 190}},
											        {'score': 0.7_218, 'label': 'remote', 'box': {'xmin': 204, 'ymin': 167, 'xmax': 232, 'ymax': 190}},
											        {'score': 0.7_184, 'label': 'couch', 'box': {'xmin': 204, 'ymin': 167, 'xmax': 232, 'ymax': 190}},
											        {'score': 0.6_748, 'label': 'remote', 'box': {'xmin': 571, 'ymin': 83, 'xmax': 598, 'ymax': 103}},
											        {'score': 0.6_656, 'label': 'cat', 'box': {'xmin': 571, 'ymin': 83, 'xmax': 598, 'ymax': 103}},
											        {'score': 0.6_614, 'label': 'couch', 'box': {'xmin': 571, 'ymin': 83, 'xmax': 598, 'ymax': 103}},
											        {'score': 0.6_456, 'label': 'remote', 'box': {'xmin': 494, 'ymin': 105, 'xmax': 521, 'ymax': 127}},
											        {'score': 0.642, 'label': 'remote', 'box': {'xmin': 67, 'ymin': 274, 'xmax': 93, 'ymax': 297}},
											        {'score': 0.6_419, 'label': 'cat', 'box': {'xmin': 494, 'ymin': 105, 'xmax': 521, 'ymax': 127}},
											    ],     )

											SCREAMING_SNAKE_CASE_				=				object_detector(
											    [
											        {
											            'image': './tests/fixtures/tests_samples/COCO/000000039769.png',
											            'candidate_labels': ['cat', 'remote', 'couch'],
											        }
											    ],     threshold=0.64,     )

											self.assertEqual(
											    nested_simplify(_lowercase,     decimals=4       ),     [
											        [
											            {'score': 0.7_235, 'label': 'cat', 'box': {'xmin': 204, 'ymin': 167, 'xmax': 232, 'ymax': 190}},
											            {'score': 0.7_218, 'label': 'remote', 'box': {'xmin': 204, 'ymin': 167, 'xmax': 232, 'ymax': 190}},
											            {'score': 0.7_184, 'label': 'couch', 'box': {'xmin': 204, 'ymin': 167, 'xmax': 232, 'ymax': 190}},
											            {'score': 0.6_748, 'label': 'remote', 'box': {'xmin': 571, 'ymin': 83, 'xmax': 598, 'ymax': 103}},
											            {'score': 0.6_656, 'label': 'cat', 'box': {'xmin': 571, 'ymin': 83, 'xmax': 598, 'ymax': 103}},
											            {'score': 0.6_614, 'label': 'couch', 'box': {'xmin': 571, 'ymin': 83, 'xmax': 598, 'ymax': 103}},
											            {'score': 0.6_456, 'label': 'remote', 'box': {'xmin': 494, 'ymin': 105, 'xmax': 521, 'ymax': 127}},
											            {'score': 0.642, 'label': 'remote', 'box': {'xmin': 67, 'ymin': 274, 'xmax': 93, 'ymax': 297}},
											            {'score': 0.6_419, 'label': 'cat', 'box': {'xmin': 494, 'ymin': 105, 'xmax': 521, 'ymax': 127}},
											        ]
											    ],     )



				@require_torch
				@slow
				def   a__					(    self       )     ->							Optional[int]:
											SCREAMING_SNAKE_CASE_				=				pipeline('zero-shot-object-detection'       )

											SCREAMING_SNAKE_CASE_				=				object_detector(
											    'http://images.cocodataset.org/val2017/000000039769.jpg',     candidate_labels=['cat', 'remote', 'couch'],     )
											self.assertEqual(
											    nested_simplify(_lowercase,     decimals=4       ),     [
											        {'score': 0.2_868, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}},
											        {'score': 0.277, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 72, 'xmax': 177, 'ymax': 115}},
											        {'score': 0.2_537, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}},
											        {'score': 0.1_474, 'label': 'remote', 'box': {'xmin': 335, 'ymin': 74, 'xmax': 371, 'ymax': 187}},
											        {'score': 0.1_208, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}},
											    ],     )

											SCREAMING_SNAKE_CASE_				=				object_detector(
											    [
											        {
											            'image': 'http://images.cocodataset.org/val2017/000000039769.jpg',
											            'candidate_labels': ['cat', 'remote', 'couch'],
											        },
											        {
											            'image': 'http://images.cocodataset.org/val2017/000000039769.jpg',
											            'candidate_labels': ['cat', 'remote', 'couch'],
											        },
											    ],     )
											self.assertEqual(
											    nested_simplify(_lowercase,     decimals=4       ),     [
											        [
											            {'score': 0.2_868, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}},
											            {'score': 0.277, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 72, 'xmax': 177, 'ymax': 115}},
											            {'score': 0.2_537, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}},
											            {'score': 0.1_474, 'label': 'remote', 'box': {'xmin': 335, 'ymin': 74, 'xmax': 371, 'ymax': 187}},
											            {'score': 0.1_208, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}},
											        ],
											        [
											            {'score': 0.2_868, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}},
											            {'score': 0.277, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 72, 'xmax': 177, 'ymax': 115}},
											            {'score': 0.2_537, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}},
											            {'score': 0.1_474, 'label': 'remote', 'box': {'xmin': 335, 'ymin': 74, 'xmax': 371, 'ymax': 187}},
											            {'score': 0.1_208, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}},
											        ],
											    ],     )



				@require_tf
				@unittest.skip('Zero Shot Object Detection not implemented in TF'       )
				def   a__					(    self       )     ->							Optional[Any]:
											pass



				@require_torch
				@slow
				def   a__					(    self       )     ->							Any:
											SCREAMING_SNAKE_CASE_				=				0.2
											SCREAMING_SNAKE_CASE_				=				pipeline('zero-shot-object-detection'       )

											SCREAMING_SNAKE_CASE_				=				object_detector(
											    'http://images.cocodataset.org/val2017/000000039769.jpg',     candidate_labels=['cat', 'remote', 'couch'],     threshold=_lowercase,     )
											self.assertEqual(
											    nested_simplify(_lowercase,     decimals=4       ),     [
											        {'score': 0.2_868, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}},
											        {'score': 0.277, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 72, 'xmax': 177, 'ymax': 115}},
											        {'score': 0.2_537, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}},
											    ],     )





				@require_torch
				@slow
				def   a__					(    self       )     ->							int:
											SCREAMING_SNAKE_CASE_				=				2
											SCREAMING_SNAKE_CASE_				=				pipeline('zero-shot-object-detection'       )

											SCREAMING_SNAKE_CASE_				=				object_detector(
											    'http://images.cocodataset.org/val2017/000000039769.jpg',     candidate_labels=['cat', 'remote', 'couch'],     top_k=_lowercase,     )
											self.assertEqual(
											    nested_simplify(_lowercase,     decimals=4       ),     [
											        {'score': 0.2_868, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}},
											        {'score': 0.277, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 72, 'xmax': 177, 'ymax': 115}},
											    ],     )





