




import unittest

import numpy as np

from transformers import BlipTextConfig
from transformers.testing_utils import require_torch, slow, torch_device
from transformers.utils import is_torch_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask


if is_torch_available():
      import torch

      from transformers import BlipTextModel
      from transformers.models.blip.modeling_blip import BLIP_PRETRAINED_MODEL_ARCHIVE_LIST






class 	A	:
     """simple docstring"""

     def __init__(			self     :      Optional[Any]		,     A__     :      str		,     A__     :      List[str]=1_2		,     A__     :      List[Any]=7		,     A__     :      Optional[Any]=True		,     A__     :      str=True		,     A__     :      int=True		,     A__     :      List[Any]=9_9		,     A__     :      Dict=3_2		,     A__     :      List[str]=3_2		,     A__     :      Optional[Any]=5		,     A__     :      int=4		,     A__     :      Tuple=3_7		,     A__     :      Any=0.1		,     A__     :      Any=0.1		,     A__     :      Union[str, Any]=5_1_2		,     A__     :      Union[str, Any]=0.02		,     A__     :      int=0		,     A__     :      Optional[Any]=None		,     ) ->				List[str]:
           lowerCamelCase__					     = parent
           lowerCamelCase__					     = batch_size
           lowerCamelCase__					     = seq_length
           lowerCamelCase__					     = is_training
           lowerCamelCase__					     = use_input_mask
           lowerCamelCase__					     = use_labels
           lowerCamelCase__					     = vocab_size
           lowerCamelCase__					     = hidden_size
           lowerCamelCase__					     = projection_dim
           lowerCamelCase__					     = num_hidden_layers
           lowerCamelCase__					     = num_attention_heads
           lowerCamelCase__					     = intermediate_size
           lowerCamelCase__					     = dropout
           lowerCamelCase__					     = attention_dropout
           lowerCamelCase__					     = max_position_embeddings
           lowerCamelCase__					     = initializer_range
           lowerCamelCase__					     = scope
           lowerCamelCase__					     = bos_token_id




     def        __snake_case      (			self     :      Optional[Any]	) ->				str:
           lowerCamelCase__					     = ids_tensor([self.batch_size, self.seq_length]		,     self.vocab_size	)

           lowerCamelCase__					     = None
           if self.use_input_mask:
                 lowerCamelCase__					     = random_attention_mask([self.batch_size, self.seq_length]	)

           if input_mask is not None:
                 lowerCamelCase__     ,						lowerCamelCase__					     = input_mask.shape
                 lowerCamelCase__					     = np.random.randint(1		,     seq_length - 1		,     size=(batch_size,)	)
                 for batch_idx, start_index in enumerate(A__	):
                       lowerCamelCase__					     = 1
                       lowerCamelCase__					     = 0

           lowerCamelCase__					     = self.get_config()

           return config, input_ids, input_mask




     def        __snake_case      (			self     :      Any	) ->				Optional[Any]:
           return BlipTextConfig(
               vocab_size=self.vocab_size		,     hidden_size=self.hidden_size		,     projection_dim=self.projection_dim		,     num_hidden_layers=self.num_hidden_layers		,     num_attention_heads=self.num_attention_heads		,     intermediate_size=self.intermediate_size		,     dropout=self.dropout		,     attention_dropout=self.attention_dropout		,     max_position_embeddings=self.max_position_embeddings		,     initializer_range=self.initializer_range		,     bos_token_id=self.bos_token_id		,     )




     def        __snake_case      (			self     :      Optional[int]		,     A__     :      Any		,     A__     :      List[Any]		,     A__     :      str	) ->				Optional[Any]:
           lowerCamelCase__					     = BlipTextModel(config=A__	)
           model.to(A__	)
           model.eval()
           with torch.no_grad():
                 lowerCamelCase__					     = model(A__		,     attention_mask=A__	)
                 lowerCamelCase__					     = model(A__	)
           self.parent.assertEqual(result.last_hidden_state.shape		,     (self.batch_size, self.seq_length, self.hidden_size)	)
           self.parent.assertEqual(result.pooler_output.shape		,     (self.batch_size, self.hidden_size)	)




     def        __snake_case      (			self     :      Optional[int]	) ->				int:
           lowerCamelCase__					     = self.prepare_config_and_inputs()
           lowerCamelCase__     ,						lowerCamelCase__     ,						lowerCamelCase__					     = config_and_inputs
           lowerCamelCase__					     = {'input_ids': input_ids, 'attention_mask': input_mask}
           return config, inputs_dict






@require_torch
class 	A	(						_lowerCAmelCase	,  unittest.TestCase						):
     """simple docstring"""

     _snake_case:		int   =(BlipTextModel,) if is_torch_available() else ()
     _snake_case:		int   =False
     _snake_case:		Optional[Any]   =False
     _snake_case:		Dict   =False




     def        __snake_case      (			self     :      Any	) ->				Optional[int]:
           lowerCamelCase__					     = BlipTextModelTester(self	)
           lowerCamelCase__					     = ConfigTester(self		,     config_class=A__		,     hidden_size=3_7	)




     def        __snake_case      (			self     :      Union[str, Any]	) ->				List[Any]:
           self.config_tester.run_common_tests()




     def        __snake_case      (			self     :      List[str]	) ->				Tuple:
           lowerCamelCase__					     = self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*A__	)




     def        __snake_case      (			self     :      int	) ->				Tuple:
           pass




     def        __snake_case      (			self     :      Union[str, Any]	) ->				str:
           pass




     @unittest.skip(reason='Blip does not use inputs_embeds'	)
     def        __snake_case      (			self     :      str	) ->				Any:
           pass




     @unittest.skip(reason='BlipTextModel has no base class and is not available in MODEL_MAPPING'	)
     def        __snake_case      (			self     :      Optional[int]	) ->				Tuple:
           pass




     @unittest.skip(reason='BlipTextModel has no base class and is not available in MODEL_MAPPING'	)
     def        __snake_case      (			self     :      Union[str, Any]	) ->				List[Any]:
           pass




     @slow
     def        __snake_case      (			self     :      Any	) ->				Union[str, Any]:
           for model_name in BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 lowerCamelCase__					     = BlipTextModel.from_pretrained(A__	)
                 self.assertIsNotNone(A__	)




     def        __snake_case      (			self     :      List[str]	) ->				Union[str, Any]:
           super().test_pt_tf_model_equivalence(allow_missing_keys=A__	)





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


__SCREAMING_SNAKE_CASE			:      Union[str, Any]      			=datasets.utils.logging.get_logger(__name__)






@dataclass
class 	A	(						datasets.BuilderConfig						):
     """simple docstring"""

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




     def        __snake_case      (			self     :      Optional[Any]	) ->				Union[str, Any]:
           if self.sql is None:
                 raise ValueError('sql must be specified'	)
           if self.con is None:
                 raise ValueError('con must be specified'	)




     def        __snake_case      (			self     :      List[Any]		,     A__     :      dict		,     A__     :      Optional[datasets.Features] = None		,     ) ->				str:
           lowerCamelCase__					     = 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
           lowerCamelCase__					     = config_kwargs['sql']
           if not isinstance(A__		,     A__	):
                 if datasets.config.SQLALCHEMY_AVAILABLE and "sqlalchemy" in sys.modules:
                       import sqlalchemy

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

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




     @property
     def        __snake_case      (			self     :      Any	) ->				Union[str, Any]:
           lowerCamelCase__					     = {
               '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 	A	(						datasets.ArrowBasedBuilder						):
     """simple docstring"""

     _snake_case:		List[str]   =SqlConfig




     def        __snake_case      (			self     :      Tuple	) ->				Dict:
           return datasets.DatasetInfo(features=self.config.features	)




     def        __snake_case      (			self     :      List[Any]		,     A__     :      Any	) ->				List[Any]:
           return [datasets.SplitGenerator(name=datasets.Split.TRAIN		,     gen_kwargs={}	)]




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




     def        __snake_case      (			self     :      int	) ->				List[Any]:
           lowerCamelCase__					     = self.config.chunksize
           lowerCamelCase__					     = pd.read_sql(
               self.config.sql		,     self.config.con		,     chunksize=A__		,     **self.config.pd_read_sql_kwargs	)
           lowerCamelCase__					     = [sql_reader] if chunksize is None else sql_reader
           for chunk_idx, df in enumerate(A__	):
                 lowerCamelCase__					     = pa.Table.from_pandas(A__	)
                 yield chunk_idx, self._cast_table(A__	)