




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 						SCREAMING_SNAKE_CASE__		:
     def __init__(	self  :		int					,	__lowerCamelCase  :		List[Any]					,	__lowerCamelCase  :		Any=12					,	__lowerCamelCase  :		Any=7					,	__lowerCamelCase  :		Optional[Any]=True					,	__lowerCamelCase  :		Union[str, Any]=True					,	__lowerCamelCase  :		Dict=True					,	__lowerCamelCase  :		Any=99					,	__lowerCamelCase  :		Optional[Any]=32					,	__lowerCamelCase  :		Union[str, Any]=32					,	__lowerCamelCase  :		int=5					,	__lowerCamelCase  :		List[Any]=4					,	__lowerCamelCase  :		Tuple=37					,	__lowerCamelCase  :		str=0.1					,	__lowerCamelCase  :		str=0.1					,	__lowerCamelCase  :		int=5_12					,	__lowerCamelCase  :		str=0.02					,	__lowerCamelCase  :		List[Any]=0					,	__lowerCamelCase  :		List[Any]=None					,	):



       """simple docstring"""
       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 					A__			(	self  :		List[Any]	):



       """simple docstring"""
       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(__lowerCamelCase	):
           lowerCAmelCase__								=			1
           lowerCAmelCase__								=			0

       lowerCAmelCase__								=			self.get_config()

       return config, input_ids, input_mask
     def 					A__			(	self  :		int	):



       """simple docstring"""
       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 					A__			(	self  :		Union[str, Any]					,	__lowerCamelCase  :		Tuple					,	__lowerCamelCase  :		Dict					,	__lowerCamelCase  :		int	):



       """simple docstring"""
       lowerCAmelCase__								=			BlipTextModel(config=__lowerCamelCase	)
       model.to(__lowerCamelCase	)
       model.eval()
       with torch.no_grad():
         lowerCAmelCase__								=			model(__lowerCamelCase					,	attention_mask=__lowerCamelCase	)
         lowerCAmelCase__								=			model(__lowerCamelCase	)
       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 					A__			(	self  :		Tuple	):



       """simple docstring"""
       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 						SCREAMING_SNAKE_CASE__		(_a						,				unittest.TestCase ):
     lowercase_   :			Any   =   (BlipTextModel,) if is_torch_available() else ()
     lowercase_   :			Any   =   False
     lowercase_   :			Optional[Any]   =   False
     lowercase_   :			List[Any]   =   False
     def 					A__			(	self  :		int	):



       """simple docstring"""
       lowerCAmelCase__								=			BlipTextModelTester(self	)
       lowerCAmelCase__								=			ConfigTester(self					,	config_class=__lowerCamelCase					,	hidden_size=37	)
     def 					A__			(	self  :		int	):



       """simple docstring"""
       self.config_tester.run_common_tests()
     def 					A__			(	self  :		List[Any]	):



       """simple docstring"""
       lowerCAmelCase__								=			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__lowerCamelCase	)
     def 					A__			(	self  :		str	):



       """simple docstring"""
       pass
     def 					A__			(	self  :		Optional[int]	):



       """simple docstring"""
       pass
     @unittest.skip(reason='''Blip does not use inputs_embeds'''	)
     def 					A__			(	self  :		int	):



       """simple docstring"""
       pass
     @unittest.skip(reason='''BlipTextModel has no base class and is not available in MODEL_MAPPING'''	)
     def 					A__			(	self  :		Optional[Any]	):



       """simple docstring"""
       pass
     @unittest.skip(reason='''BlipTextModel has no base class and is not available in MODEL_MAPPING'''	)
     def 					A__			(	self  :		List[str]	):



       """simple docstring"""
       pass
     @slow
     def 					A__			(	self  :		Optional[int]	):



       """simple docstring"""
       for model_name in BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         lowerCAmelCase__								=			BlipTextModel.from_pretrained(__lowerCamelCase	)
         self.assertIsNotNone(__lowerCamelCase	)



     def 					A__			(	self  :		str	):



       """simple docstring"""
       super().test_pt_tf_model_equivalence(allow_missing_keys=__lowerCamelCase	)







import importlib
import inspect
from functools import wraps
from typing import TYPE_CHECKING, Optional, Union

from .download.streaming_download_manager import (
    xbasename,
    xdirname,
    xet_parse,
    xexists,
    xgetsize,
    xglob,
    xgzip_open,
    xisdir,
    xisfile,
    xjoin,
    xlistdir,
    xnumpy_load,
    xopen,
    xpandas_read_csv,
    xpandas_read_excel,
    xPath,
    xrelpath,
    xsio_loadmat,
    xsplit,
    xsplitext,
    xwalk,
    xxml_dom_minidom_parse,
)
from .utils.logging import get_logger
from .utils.patching import patch_submodule
from .utils.py_utils import get_imports


__magic_name__     :     List[Any]  							=					get_logger(__name__)


if TYPE_CHECKING:
      from .builder import DatasetBuilder
def 		a_       (   __lowerCAmelCase      ,   __lowerCAmelCase = None							):
  lowerCAmelCase__								=			importlib.import_module(__lowerCAmelCase							)

  # TODO(QL): always update the module to add subsequent new authentication
  if hasattr(__lowerCAmelCase      ,   '''_patched_for_streaming'''							) and module._patched_for_streaming:
    return

  def wrap_auth(__lowerCAmelCase							):
    @wraps(__lowerCAmelCase							)
    def wrapper(*__lowerCAmelCase      ,   **__lowerCAmelCase							):
      return function(*__lowerCAmelCase      ,   use_auth_token=__lowerCAmelCase      ,   **__lowerCAmelCase							)

    lowerCAmelCase__								=			'''wrap_auth'''
    return wrapper

  # open files in a streaming fashion
  patch_submodule(__lowerCAmelCase      ,   '''open'''      ,   wrap_auth(__lowerCAmelCase							)							).start()
  patch_submodule(__lowerCAmelCase      ,   '''os.listdir'''      ,   wrap_auth(__lowerCAmelCase							)							).start()
  patch_submodule(__lowerCAmelCase      ,   '''os.walk'''      ,   wrap_auth(__lowerCAmelCase							)							).start()
  patch_submodule(__lowerCAmelCase      ,   '''glob.glob'''      ,   wrap_auth(__lowerCAmelCase							)							).start()
  # allow to navigate in remote zip files
  patch_submodule(__lowerCAmelCase      ,   '''os.path.join'''      ,   __lowerCAmelCase							).start()
  patch_submodule(__lowerCAmelCase      ,   '''os.path.dirname'''      ,   __lowerCAmelCase							).start()
  patch_submodule(__lowerCAmelCase      ,   '''os.path.basename'''      ,   __lowerCAmelCase							).start()
  patch_submodule(__lowerCAmelCase      ,   '''os.path.relpath'''      ,   __lowerCAmelCase							).start()
  patch_submodule(__lowerCAmelCase      ,   '''os.path.split'''      ,   __lowerCAmelCase							).start()
  patch_submodule(__lowerCAmelCase      ,   '''os.path.splitext'''      ,   __lowerCAmelCase							).start()
  # allow checks on paths
  patch_submodule(__lowerCAmelCase      ,   '''os.path.exists'''      ,   wrap_auth(__lowerCAmelCase							)							).start()
  patch_submodule(__lowerCAmelCase      ,   '''os.path.isdir'''      ,   wrap_auth(__lowerCAmelCase							)							).start()
  patch_submodule(__lowerCAmelCase      ,   '''os.path.isfile'''      ,   wrap_auth(__lowerCAmelCase							)							).start()
  patch_submodule(__lowerCAmelCase      ,   '''os.path.getsize'''      ,   wrap_auth(__lowerCAmelCase							)							).start()
  patch_submodule(__lowerCAmelCase      ,   '''pathlib.Path'''      ,   __lowerCAmelCase							).start()
  # file readers
  patch_submodule(__lowerCAmelCase      ,   '''gzip.open'''      ,   wrap_auth(__lowerCAmelCase							)							).start()
  patch_submodule(__lowerCAmelCase      ,   '''numpy.load'''      ,   wrap_auth(__lowerCAmelCase							)							).start()
  patch_submodule(__lowerCAmelCase      ,   '''pandas.read_csv'''      ,   wrap_auth(__lowerCAmelCase							)      ,   attrs=['''__version__''']							).start()
  patch_submodule(__lowerCAmelCase      ,   '''pandas.read_excel'''      ,   wrap_auth(__lowerCAmelCase							)      ,   attrs=['''__version__''']							).start()
  patch_submodule(__lowerCAmelCase      ,   '''scipy.io.loadmat'''      ,   wrap_auth(__lowerCAmelCase							)      ,   attrs=['''__version__''']							).start()
  patch_submodule(__lowerCAmelCase      ,   '''xml.etree.ElementTree.parse'''      ,   wrap_auth(__lowerCAmelCase							)							).start()
  patch_submodule(__lowerCAmelCase      ,   '''xml.dom.minidom.parse'''      ,   wrap_auth(__lowerCAmelCase							)							).start()
  lowerCAmelCase__								=			True




def 		a_       (   __lowerCAmelCase							):
  extend_module_for_streaming(builder.__module__      ,   use_auth_token=builder.use_auth_token							)
  # if needed, we also have to extend additional internal imports (like wmt14 -> wmt_utils)
  if not builder.__module__.startswith('''datasets.'''							):  # check that it's not a packaged builder like csv
    for imports in get_imports(inspect.getfile(builder.__class__							)							):
      if imports[0] == "internal":
        lowerCAmelCase__								=			imports[1]
        lowerCAmelCase__								=			'''.'''.join(builder.__module__.split('''.'''							)[:-1] + [internal_import_name]							)
        extend_module_for_streaming(__lowerCAmelCase      ,   use_auth_token=builder.use_auth_token							)

    # builders can inherit from other builders that might use streaming functionality
    # (for example, ImageFolder and AudioFolder inherit from FolderBuilder which implements examples generation)
    # but these parents builders are not patched automatically as they are not instantiated, so we patch them here
  from .builder import DatasetBuilder

  lowerCAmelCase__								=			[
      cls.__module__
      for cls in type(__lowerCAmelCase							).__mro__[1:]  # make sure it's not the same module we've already patched
      if issubclass(cls      ,   __lowerCAmelCase							) and cls.__module__ != DatasetBuilder.__module__
  ]  # check it's not a standard builder from datasets.builder
  for module in parent_builder_modules:
    extend_module_for_streaming(__lowerCAmelCase      ,   use_auth_token=builder.use_auth_token							)

