


import sys
from dataclasses import dataclass
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, 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


if TYPE_CHECKING:
       import sqlitea

       import sqlalchemy


__UpperCamelCase					:	Tuple          =				datasets.utils.logging.get_logger(__name__)





@dataclass
class 			lowerCAmelCase__(     datasets.BuilderConfig    ):






    '''simple docstring'''





    A_	:  Union[str, "sqlalchemy.sql.Selectable"]								=			None
    A_	:  Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"]								=			None
    A_	:  Optional[Union[str, List[str]]]								=			None
    A_	:  bool								=			True
    A_	:  Optional[Union[List, Tuple, Dict]]								=			None
    A_	:  Optional[Union[List, Dict]]								=			None
    A_	:  Optional[List[str]]								=			None
    A_	:  Optional[int]								=			1_0_0_0_0
    A_	:  Optional[datasets.Features]								=			None





    def        _lowerCamelCase			(						self					: int						):





       '''simple docstring'''
       if self.sql is None:
          raise ValueError('''sql must be specified'''						)
       if self.con is None:
          raise ValueError('''con must be specified'''						)





    def        _lowerCamelCase			(						self					: List[str]							, __snake_case					: dict							, __snake_case					: Optional[datasets.Features] = None							, ):





       '''simple docstring'''
       UpperCAmelCase_				:   str							= config_kwargs.copy()
       # We need to stringify the Selectable object to make its hash deterministic

       # The process of stringifying is explained here: http://docs.sqlalchemy.org/en/latest/faq/sqlexpressions.html
       UpperCAmelCase_				:   Optional[int]							= config_kwargs['''sql''']
       if not isinstance(__snake_case							, __snake_case						):
          if datasets.config.SQLALCHEMY_AVAILABLE and "sqlalchemy" in sys.modules:
             import sqlalchemy

             if isinstance(__snake_case							, sqlalchemy.sql.Selectable						):
                UpperCAmelCase_				:   List[Any]							= sqlalchemy.create_engine(config_kwargs['''con'''].split('''://'''						)[0] + '''://'''						)
                UpperCAmelCase_				:   List[str]							= str(sql.compile(dialect=engine.dialect						)						)
                UpperCAmelCase_				:   Optional[Any]							= sql_str
             else:
                raise TypeError(
                    f'''Supported types for \'sql\' are string and sqlalchemy.sql.Selectable but got {type(__snake_case						)}: {sql}'''						)
          else:
             raise TypeError(
                 f'''Supported types for \'sql\' are string and sqlalchemy.sql.Selectable but got {type(__snake_case						)}: {sql}'''						)
       UpperCAmelCase_				:   Union[str, Any]							= config_kwargs['''con''']
       if not isinstance(__snake_case							, __snake_case						):
          UpperCAmelCase_				:   List[str]							= id(__snake_case						)
          logger.info(
              f'''SQL connection \'con\' of type {type(__snake_case						)} couldn\'t be hashed properly. To enable hashing, specify \'con\' as URI string instead.'''						)

       return super().create_config_id(__snake_case							, custom_features=__snake_case						)





    @property
    def        _lowerCamelCase			(						self					: List[str]						):





       '''simple docstring'''
       UpperCAmelCase_				:   Union[str, Any]							= {
           '''index_col''': self.index_col,
           '''columns''': self.columns,
           '''params''': self.params,
           '''coerce_float''': self.coerce_float,
           '''parse_dates''': self.parse_dates,
       }
       return pd_read_sql_kwargs





class 			lowerCAmelCase__(     datasets.ArrowBasedBuilder    ):






    '''simple docstring'''





    A_	:  Dict								=			SqlConfig





    def        _lowerCamelCase			(						self					: List[str]						):





       '''simple docstring'''
       return datasets.DatasetInfo(features=self.config.features						)





    def        _lowerCamelCase			(						self					: Optional[Any]							, __snake_case					: int						):





       '''simple docstring'''
       return [datasets.SplitGenerator(name=datasets.Split.TRAIN							, gen_kwargs={}						)]





    def        _lowerCamelCase			(						self					: int							, __snake_case					: pa.Table						):





       '''simple docstring'''
       if self.config.features is not None:
          UpperCAmelCase_				:   Optional[Any]							= self.config.features.arrow_schema
          if all(not require_storage_cast(__snake_case						) for feature in self.config.features.values()						):
             # cheaper cast
             UpperCAmelCase_				:   Union[str, Any]							= pa.Table.from_arrays([pa_table[field.name] for field in schema]							, schema=__snake_case						)
          else:
             # more expensive cast; allows str <-> int/float or str to Audio for example
             UpperCAmelCase_				:   List[str]							= table_cast(__snake_case							, __snake_case						)
       return pa_table





    def        _lowerCamelCase			(						self					: Optional[int]						):





       '''simple docstring'''
       UpperCAmelCase_				:   str							= self.config.chunksize
       UpperCAmelCase_				:   List[Any]							= pd.read_sql(
           self.config.sql							, self.config.con							, chunksize=__snake_case							, **self.config.pd_read_sql_kwargs						)
       UpperCAmelCase_				:   str							= [sql_reader] if chunksize is None else sql_reader
       for chunk_idx, df in enumerate(__snake_case						):
          UpperCAmelCase_				:   Dict							= pa.Table.from_pandas(__snake_case						)
          yield chunk_idx, self._cast_table(__snake_case						)



'''simple docstring'''



import inspect
import unittest

from transformers import EfficientNetConfig
from transformers.testing_utils import is_pipeline_test, require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch

      from transformers import EfficientNetForImageClassification, EfficientNetModel
      from transformers.models.efficientnet.modeling_efficientnet import EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import AutoImageProcessor



class       a							:


     """simple docstring"""






     def __init__(							self	:						int				,					snake_case	:						str				,					snake_case	:						str=13				,					snake_case	:						List[str]=32				,					snake_case	:						Tuple=3				,					snake_case	:						Dict=[3, 3, 5]				,					snake_case	:						Tuple=[32, 16, 24]				,					snake_case	:						Any=[16, 24, 40]				,					snake_case	:						Dict=[1, 1, 2]				,					snake_case	:						Optional[int]=[1, 1, 2]				,					snake_case	:						Optional[int]=[1, 6, 6]				,					snake_case	:						List[str]=True				,					snake_case	:						int=True				,					snake_case	:						Tuple=37				,					snake_case	:						List[str]="gelu"				,					snake_case	:						Optional[int]=10				,					)		->				Optional[int]:
          __UpperCAmelCase      :					Union[str, Any]    				=     parent
          __UpperCAmelCase      :					Optional[int]    				=     batch_size
          __UpperCAmelCase      :					Union[str, Any]    				=     image_size
          __UpperCAmelCase      :					List[Any]    				=     num_channels
          __UpperCAmelCase      :					str    				=     kernel_sizes
          __UpperCAmelCase      :					Union[str, Any]    				=     in_channels
          __UpperCAmelCase      :					str    				=     out_channels
          __UpperCAmelCase      :					List[str]    				=     strides
          __UpperCAmelCase      :					List[str]    				=     num_block_repeats
          __UpperCAmelCase      :					List[str]    				=     expand_ratios
          __UpperCAmelCase      :					Union[str, Any]    				=     is_training
          __UpperCAmelCase      :					Optional[int]    				=     hidden_act
          __UpperCAmelCase      :					List[Any]    				=     num_labels
          __UpperCAmelCase      :					Dict    				=     use_labels

     def 					lowerCamelCase__					(							self	:						Dict     )		->				Tuple:
          __UpperCAmelCase      :					Tuple    				=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

          __UpperCAmelCase      :					int    				=     None
          if self.use_labels:
               __UpperCAmelCase      :					Optional[Any]    				=     ids_tensor([self.batch_size]				,					self.num_labels     )

          __UpperCAmelCase      :					int    				=     self.get_config()
          return config, pixel_values, labels

     def 					lowerCamelCase__					(							self	:						str     )		->				Dict:
          return EfficientNetConfig(
              num_channels=self.num_channels				,					kernel_sizes=self.kernel_sizes				,					in_channels=self.in_channels				,					out_channels=self.out_channels				,					strides=self.strides				,					num_block_repeats=self.num_block_repeats				,					expand_ratios=self.expand_ratios				,					hidden_act=self.hidden_act				,					num_labels=self.num_labels				,					)

     def 					lowerCamelCase__					(							self	:						Any				,					snake_case	:						Tuple				,					snake_case	:						Tuple				,					snake_case	:						Optional[int]     )		->				Union[str, Any]:
          __UpperCAmelCase      :					Union[str, Any]    				=     EfficientNetModel(config=snake_case     )
          model.to(snake_case     )
          model.eval()
          __UpperCAmelCase      :					Union[str, Any]    				=     model(snake_case     )
          # expected last hidden states: B, C, H // 4, W // 4
          self.parent.assertEqual(
              result.last_hidden_state.shape				,					(self.batch_size, config.hidden_dim, self.image_size // 4, self.image_size // 4)				,					)

     def 					lowerCamelCase__					(							self	:						List[str]				,					snake_case	:						Optional[int]				,					snake_case	:						List[str]				,					snake_case	:						List[str]     )		->				Optional[int]:
          __UpperCAmelCase      :					List[str]    				=     EfficientNetForImageClassification(snake_case     )
          model.to(snake_case     )
          model.eval()
          __UpperCAmelCase      :					Any    				=     model(snake_case				,					labels=snake_case     )
          self.parent.assertEqual(result.logits.shape				,					(self.batch_size, self.num_labels)     )






     def 					lowerCamelCase__					(							self	:						str     )		->				Tuple:
          __UpperCAmelCase      :					List[Any]    				=     self.prepare_config_and_inputs()
          __UpperCAmelCase				,  __UpperCAmelCase				,  __UpperCAmelCase      :					Union[str, Any]    				=     config_and_inputs
          __UpperCAmelCase      :					Union[str, Any]    				=     {'''pixel_values''': pixel_values}
          return config, inputs_dict



@require_torch
class       a							(						_a      ,    _a      ,    unittest.TestCase			):


     """simple docstring"""






     SCREAMING_SNAKE_CASE			:					str				  =  (EfficientNetModel, EfficientNetForImageClassification) if is_torch_available() else ()
     SCREAMING_SNAKE_CASE			:					List[str]				  =  (
         {"feature-extraction": EfficientNetModel, "image-classification": EfficientNetForImageClassification}
         if is_torch_available()
         else {}
     )

     SCREAMING_SNAKE_CASE			:					Union[str, Any]				  =  False
     SCREAMING_SNAKE_CASE			:					Optional[int]				  =  False
     SCREAMING_SNAKE_CASE			:					Optional[int]				  =  False
     SCREAMING_SNAKE_CASE			:					List[Any]				  =  False
     SCREAMING_SNAKE_CASE			:					List[str]				  =  False

     def 					lowerCamelCase__					(							self	:						List[str]     )		->				List[str]:
          __UpperCAmelCase      :					Dict    				=     EfficientNetModelTester(self     )
          __UpperCAmelCase      :					Optional[Any]    				=     ConfigTester(
              self				,					config_class=snake_case				,					has_text_modality=snake_case				,					hidden_size=37     )

     def 					lowerCamelCase__					(							self	:						List[str]     )		->				str:
          self.create_and_test_config_common_properties()
          self.config_tester.create_and_test_config_to_json_string()
          self.config_tester.create_and_test_config_to_json_file()
          self.config_tester.create_and_test_config_from_and_save_pretrained()
          self.config_tester.create_and_test_config_with_num_labels()
          self.config_tester.check_config_can_be_init_without_params()
          self.config_tester.check_config_arguments_init()

     def 					lowerCamelCase__					(							self	:						Dict     )		->				str:
          return

     @unittest.skip(reason='''EfficientNet does not use inputs_embeds'''     )
     def 					lowerCamelCase__					(							self	:						List[Any]     )		->				Optional[int]:
          pass

     @unittest.skip(reason='''EfficientNet does not support input and output embeddings'''     )
     def 					lowerCamelCase__					(							self	:						List[str]     )		->				Dict:
          pass

     @unittest.skip(reason='''EfficientNet does not use feedforward chunking'''     )
     def 					lowerCamelCase__					(							self	:						Union[str, Any]     )		->				Optional[int]:
          pass

     def 					lowerCamelCase__					(							self	:						List[str]     )		->				Optional[Any]:
          __UpperCAmelCase				,  __UpperCAmelCase      :					List[str]    				=     self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
               __UpperCAmelCase      :					Tuple    				=     model_class(snake_case     )
               __UpperCAmelCase      :					Tuple    				=     inspect.signature(model.forward     )
               # signature.parameters is an OrderedDict => so arg_names order is deterministic
               __UpperCAmelCase      :					Optional[int]    				=     [*signature.parameters.keys()]

               __UpperCAmelCase      :					Union[str, Any]    				=     ['''pixel_values''']
               self.assertListEqual(arg_names[:1]				,					snake_case     )

     def 					lowerCamelCase__					(							self	:						int     )		->				List[str]:
          __UpperCAmelCase      :					Union[str, Any]    				=     self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*snake_case     )

     def 					lowerCamelCase__					(							self	:						int     )		->				str:
          def check_hidden_states_output(snake_case	:						Union[str, Any]				,					snake_case	:						str				,					snake_case	:						Tuple     ):
               __UpperCAmelCase      :					List[str]    				=     model_class(snake_case     )
               model.to(snake_case     )
               model.eval()

               with torch.no_grad():
                    __UpperCAmelCase      :					int    				=     model(**self._prepare_for_class(snake_case				,					snake_case     )     )

               __UpperCAmelCase      :					Optional[int]    				=     outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
               __UpperCAmelCase      :					List[str]    				=     sum(config.num_block_repeats     ) * 4
               self.assertEqual(len(snake_case     )				,					snake_case     )

               # EfficientNet's feature maps are of shape (batch_size, num_channels, height, width)
               self.assertListEqual(
                   list(hidden_states[0].shape[-2:]     )				,					[self.model_tester.image_size // 2, self.model_tester.image_size // 2]				,					)

          __UpperCAmelCase				,  __UpperCAmelCase      :					Union[str, Any]    				=     self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
               __UpperCAmelCase      :					int    				=     True
               check_hidden_states_output(snake_case				,					snake_case				,					snake_case     )

               # check that output_hidden_states also work using config
               del inputs_dict["output_hidden_states"]
               __UpperCAmelCase      :					Union[str, Any]    				=     True

               check_hidden_states_output(snake_case				,					snake_case				,					snake_case     )

     def 					lowerCamelCase__					(							self	:						str     )		->				Any:
          __UpperCAmelCase      :					Any    				=     self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*snake_case     )

     @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''     )
     def 					lowerCamelCase__					(							self	:						List[Any]     )		->				Tuple:
          pass

     @slow
     def 					lowerCamelCase__					(							self	:						Optional[int]     )		->				List[str]:
          for model_name in EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               __UpperCAmelCase      :					str    				=     EfficientNetModel.from_pretrained(snake_case     )
               self.assertIsNotNone(snake_case     )






     @is_pipeline_test
     @require_vision
     @slow
     def 					lowerCamelCase__					(							self	:						Union[str, Any]     )		->				List[str]:
          super().test_pipeline_image_classification()




def       _a      (		):





     '''simple docstring'''






     __UpperCAmelCase      :					Any    				=     Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''    )
     return image



@require_torch
@require_vision
class       a							(						unittest.TestCase			):


     """simple docstring"""






     @cached_property
     def 					lowerCamelCase__					(							self	:						List[str]     )		->				Dict:
          return AutoImageProcessor.from_pretrained('''google/efficientnet-b7'''     ) if is_vision_available() else None






     @slow
     def 					lowerCamelCase__					(							self	:						str     )		->				Any:
          __UpperCAmelCase      :					Tuple    				=     EfficientNetForImageClassification.from_pretrained('''google/efficientnet-b7'''     ).to(snake_case     )

          __UpperCAmelCase      :					List[str]    				=     self.default_image_processor
          __UpperCAmelCase      :					List[Any]    				=     prepare_img()
          __UpperCAmelCase      :					Union[str, Any]    				=     image_processor(images=snake_case				,					return_tensors='''pt'''     ).to(snake_case     )

          # forward pass
          with torch.no_grad():
               __UpperCAmelCase      :					Optional[Any]    				=     model(**snake_case     )

          # verify the logits
          __UpperCAmelCase      :					Any    				=     torch.Size((1, 1000)     )
          self.assertEqual(outputs.logits.shape				,					snake_case     )

          __UpperCAmelCase      :					Dict    				=     torch.tensor([0.0_001, 0.0_002, 0.0_002]     ).to(snake_case     )
          self.assertTrue(torch.allclose(outputs.logits[0, :3]				,					snake_case				,					atol=1E-4     )     )