






from __future__ import annotations

import unittest

import numpy as np

from transformers import BlipTextConfig
from transformers.testing_utils import require_tf, slow
from transformers.utils import is_tf_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask


if is_tf_available():
 import tensorflow as tf

 from transformers import TFBlipTextModel
 from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST





class 			__a  :







 def __init__(		self					:   List[str]							,   SCREAMING_SNAKE_CASE					:   Tuple							,   SCREAMING_SNAKE_CASE					:   Tuple=12							,   SCREAMING_SNAKE_CASE					:   Dict=7							,   SCREAMING_SNAKE_CASE					:   Optional[Any]=True							,   SCREAMING_SNAKE_CASE					:   Dict=True							,   SCREAMING_SNAKE_CASE					:   Any=True							,   SCREAMING_SNAKE_CASE					:   Optional[Any]=99							,   SCREAMING_SNAKE_CASE					:   Tuple=32							,   SCREAMING_SNAKE_CASE					:   str=32							,   SCREAMING_SNAKE_CASE					:   Union[str, Any]=2							,   SCREAMING_SNAKE_CASE					:   Dict=4							,   SCREAMING_SNAKE_CASE					:   int=37							,   SCREAMING_SNAKE_CASE					:   int=0.1							,   SCREAMING_SNAKE_CASE					:   Union[str, Any]=0.1							,   SCREAMING_SNAKE_CASE					:   Tuple=5_12							,   SCREAMING_SNAKE_CASE					:   Optional[Any]=0.0_2							,   SCREAMING_SNAKE_CASE					:   Union[str, Any]=0							,   SCREAMING_SNAKE_CASE					:   List[Any]=None							,   ):


      '''simple docstring'''






      UpperCamelCase__			:   List[Any]       				=  parent
      UpperCamelCase__			:   List[Any]       				=  batch_size
      UpperCamelCase__			:   Optional[int]       				=  seq_length
      UpperCamelCase__			:   Any       				=  is_training
      UpperCamelCase__			:   List[str]       				=  use_input_mask
      UpperCamelCase__			:   List[str]       				=  use_labels
      UpperCamelCase__			:   str       				=  vocab_size
      UpperCamelCase__			:   Dict       				=  hidden_size
      UpperCamelCase__			:   int       				=  projection_dim
      UpperCamelCase__			:   List[str]       				=  num_hidden_layers
      UpperCamelCase__			:   Tuple       				=  num_attention_heads
      UpperCamelCase__			:   str       				=  intermediate_size
      UpperCamelCase__			:   str       				=  dropout
      UpperCamelCase__			:   Tuple       				=  attention_dropout
      UpperCamelCase__			:   Optional[int]       				=  max_position_embeddings
      UpperCamelCase__			:   Union[str, Any]       				=  initializer_range
      UpperCamelCase__			:   str       				=  scope
      UpperCamelCase__			:   List[Any]       				=  bos_token_id







 def 					__lowercase					(		self					:   int						):


      '''simple docstring'''






      UpperCamelCase__			:   Optional[Any]       				=  ids_tensor([self.batch_size, self.seq_length]							,   self.vocab_size						)

      UpperCamelCase__			:   List[Any]       				=  None
      if self.use_input_mask:
           UpperCamelCase__			:   int       				=  random_attention_mask([self.batch_size, self.seq_length]						)

      if input_mask is not None:
           UpperCamelCase__			:   int       				=  input_mask.numpy()
           UpperCamelCase__				,     UpperCamelCase__			:   str       				=  input_mask.shape
           UpperCamelCase__			:   List[str]       				=  np.random.randint(1							,   seq_length - 1							,   size=(batch_size,)						)
           for batch_idx, start_index in enumerate(SCREAMING_SNAKE_CASE						):
                UpperCamelCase__			:   Union[str, Any]       				=  1
                UpperCamelCase__			:   List[Any]       				=  0

      UpperCamelCase__			:   Optional[Any]       				=  self.get_config()

      return config, input_ids, tf.convert_to_tensor(SCREAMING_SNAKE_CASE						)







 def 					__lowercase					(		self					:   Dict						):


      '''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 					__lowercase					(		self					:   Optional[int]							,   SCREAMING_SNAKE_CASE					:   Any							,   SCREAMING_SNAKE_CASE					:   Optional[Any]							,   SCREAMING_SNAKE_CASE					:   List[Any]						):


      '''simple docstring'''






      UpperCamelCase__			:   Optional[int]       				=  TFBlipTextModel(config=SCREAMING_SNAKE_CASE						)
      UpperCamelCase__			:   Optional[int]       				=  model(SCREAMING_SNAKE_CASE							,   attention_mask=SCREAMING_SNAKE_CASE							,   training=SCREAMING_SNAKE_CASE						)
      UpperCamelCase__			:   int       				=  model(SCREAMING_SNAKE_CASE							,   training=SCREAMING_SNAKE_CASE						)
      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 					__lowercase					(		self					:   int						):


      '''simple docstring'''






      UpperCamelCase__			:   Optional[int]       				=  self.prepare_config_and_inputs()
      UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__			:   int       				=  config_and_inputs
      UpperCamelCase__			:   List[Any]       				=  {"input_ids": input_ids, "attention_mask": input_mask}
      return config, inputs_dict







@require_tf
class 			__a  (    A__       ,   unittest.TestCase       ):
 _lowerCAmelCase       :       Any        = (TFBlipTextModel,) if is_tf_available() else ()
 _lowerCAmelCase       :       Union[str, Any]        = False
 _lowerCAmelCase       :       List[str]        = False
 _lowerCAmelCase       :       Optional[Any]        = False







 def 					__lowercase					(		self					:   Optional[Any]						):


      '''simple docstring'''






      UpperCamelCase__			:   Any       				=  BlipTextModelTester(self						)
      UpperCamelCase__			:   str       				=  ConfigTester(self							,   config_class=SCREAMING_SNAKE_CASE							,   hidden_size=37						)







 def 					__lowercase					(		self					:   Dict						):


      '''simple docstring'''






      self.config_tester.run_common_tests()







 def 					__lowercase					(		self					:   str						):


      '''simple docstring'''






      UpperCamelCase__			:   Union[str, Any]       				=  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE						)







 def 					__lowercase					(		self					:   Optional[int]						):


      '''simple docstring'''






      pass







 def 					__lowercase					(		self					:   Optional[Any]						):


      '''simple docstring'''






      pass







 @unittest.skip(reason="Blip does not use inputs_embeds"						)
 def 					__lowercase					(		self					:   str						):


      '''simple docstring'''






      pass







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


      '''simple docstring'''






      pass







 @unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING"						)
 def 					__lowercase					(		self					:   int						):


      '''simple docstring'''






      pass







 @slow
 def 					__lowercase					(		self					:   Dict						):


      '''simple docstring'''






      for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           UpperCamelCase__			:   Any       				=  TFBlipTextModel.from_pretrained(SCREAMING_SNAKE_CASE						)
           self.assertIsNotNone(SCREAMING_SNAKE_CASE						)







 def 					__lowercase					(		self					:   Union[str, Any]							,   SCREAMING_SNAKE_CASE					:   Tuple=True						):


      '''simple docstring'''






      super().test_pt_tf_model_equivalence(allow_missing_keys=SCREAMING_SNAKE_CASE						)







import os
import tempfile
from functools import partial
from unittest import TestCase
from unittest.mock import patch

import datasets
import datasets.config

from .utils import require_beam





class 			__a  (    datasets.BeamBasedBuilder       ):







 def 					__lowercase					(		self					:   List[str]						):


      '''simple docstring'''






      return datasets.DatasetInfo(
          features=datasets.Features({"content": datasets.Value("string"						)}						)							,   supervised_keys=SCREAMING_SNAKE_CASE							,   )







 def 					__lowercase					(		self					:   List[Any]							,   SCREAMING_SNAKE_CASE					:   Optional[int]							,   SCREAMING_SNAKE_CASE					:   Any						):


      '''simple docstring'''






      return [datasets.SplitGenerator(name=datasets.Split.TRAIN							,   gen_kwargs={"examples": get_test_dummy_examples()}						)]







 def 					__lowercase					(		self					:   List[Any]							,   SCREAMING_SNAKE_CASE					:   Tuple							,   SCREAMING_SNAKE_CASE					:   int						):


      '''simple docstring'''






      import apache_beam as beam

      return pipeline | "Load Examples" >> beam.Create(SCREAMING_SNAKE_CASE						)







class 			__a  (    datasets.BeamBasedBuilder       ):







 def 					__lowercase					(		self					:   Any						):


      '''simple docstring'''






      return datasets.DatasetInfo(
          features=datasets.Features({"a": datasets.Sequence({"b": datasets.Value("string"						)}						)}						)							,   supervised_keys=SCREAMING_SNAKE_CASE							,   )







 def 					__lowercase					(		self					:   Any							,   SCREAMING_SNAKE_CASE					:   Tuple							,   SCREAMING_SNAKE_CASE					:   List[Any]						):


      '''simple docstring'''






      return [
          datasets.SplitGenerator(name=datasets.Split.TRAIN							,   gen_kwargs={"examples": get_test_nested_examples()}						)
      ]







 def 					__lowercase					(		self					:   List[Any]							,   SCREAMING_SNAKE_CASE					:   Tuple							,   SCREAMING_SNAKE_CASE					:   Any						):


      '''simple docstring'''






      import apache_beam as beam

      return pipeline | "Load Examples" >> beam.Create(SCREAMING_SNAKE_CASE						)







def 		SCREAMING_SNAKE_CASE							(					) ->	List[str]:
     return [(i, {"content": content}) for i, content in enumerate(["foo", "bar", "foobar"]			)]







def 		SCREAMING_SNAKE_CASE							(					) ->	Optional[Any]:
     return [(i, {"a": {"b": [content]}}) for i, content in enumerate(["foo", "bar", "foobar"]			)]





class 			__a  (    A__       ):







 @require_beam
 def 					__lowercase					(		self					:   Optional[int]						):


      '''simple docstring'''






      UpperCamelCase__			:   int       				=  len(get_test_dummy_examples()						)
      with tempfile.TemporaryDirectory() as tmp_cache_dir:
           UpperCamelCase__			:   List[Any]       				=  DummyBeamDataset(cache_dir=SCREAMING_SNAKE_CASE							,   beam_runner="DirectRunner"						)
           builder.download_and_prepare()
           self.assertTrue(
               os.path.exists(
                   os.path.join(SCREAMING_SNAKE_CASE							,   builder.name							,   "default"							,   "0.0.0"							,   F'{builder.name}-train.arrow'						)						)						)
           self.assertDictEqual(builder.info.features							,   datasets.Features({"content": datasets.Value("string"						)}						)						)
           UpperCamelCase__			:   Optional[Any]       				=  builder.as_dataset()
           self.assertEqual(dset["train"].num_rows							,   SCREAMING_SNAKE_CASE						)
           self.assertEqual(dset["train"].info.splits["train"].num_examples							,   SCREAMING_SNAKE_CASE						)
           self.assertDictEqual(dset["train"][0]							,   get_test_dummy_examples()[0][1]						)
           self.assertDictEqual(
               dset["train"][expected_num_examples - 1]							,   get_test_dummy_examples()[expected_num_examples - 1][1]						)
           self.assertTrue(
               os.path.exists(os.path.join(SCREAMING_SNAKE_CASE							,   builder.name							,   "default"							,   "0.0.0"							,   "dataset_info.json"						)						)						)
           del dset







 @require_beam
 def 					__lowercase					(		self					:   Any						):


      '''simple docstring'''






      import apache_beam as beam

      UpperCamelCase__			:   Any       				=  beam.io.parquetio.WriteToParquet

      UpperCamelCase__			:   Tuple       				=  len(get_test_dummy_examples()						)
      with tempfile.TemporaryDirectory() as tmp_cache_dir:
           UpperCamelCase__			:   str       				=  DummyBeamDataset(cache_dir=SCREAMING_SNAKE_CASE							,   beam_runner="DirectRunner"						)
           with patch("apache_beam.io.parquetio.WriteToParquet"						) as write_parquet_mock:
                UpperCamelCase__			:   Optional[Any]       				=  partial(SCREAMING_SNAKE_CASE							,   num_shards=2						)
                builder.download_and_prepare()
           self.assertTrue(
               os.path.exists(
                   os.path.join(
                       SCREAMING_SNAKE_CASE							,   builder.name							,   "default"							,   "0.0.0"							,   F'{builder.name}-train-00000-of-00002.arrow'						)						)						)
           self.assertTrue(
               os.path.exists(
                   os.path.join(
                       SCREAMING_SNAKE_CASE							,   builder.name							,   "default"							,   "0.0.0"							,   F'{builder.name}-train-00000-of-00002.arrow'						)						)						)
           self.assertDictEqual(builder.info.features							,   datasets.Features({"content": datasets.Value("string"						)}						)						)
           UpperCamelCase__			:   List[Any]       				=  builder.as_dataset()
           self.assertEqual(dset["train"].num_rows							,   SCREAMING_SNAKE_CASE						)
           self.assertEqual(dset["train"].info.splits["train"].num_examples							,   SCREAMING_SNAKE_CASE						)
           # Order is not preserved when sharding, so we just check that all the elements are there
           self.assertListEqual(sorted(dset["train"]["content"]						)							,   sorted(["foo", "bar", "foobar"]						)						)
           self.assertTrue(
               os.path.exists(os.path.join(SCREAMING_SNAKE_CASE							,   builder.name							,   "default"							,   "0.0.0"							,   "dataset_info.json"						)						)						)
           del dset







 @require_beam
 def 					__lowercase					(		self					:   List[Any]						):


      '''simple docstring'''






      with tempfile.TemporaryDirectory() as tmp_cache_dir:
           UpperCamelCase__			:   int       				=  DummyBeamDataset(cache_dir=SCREAMING_SNAKE_CASE						)
           self.assertRaises(datasets.builder.MissingBeamOptions							,   builder.download_and_prepare						)







 @require_beam
 def 					__lowercase					(		self					:   List[Any]						):


      '''simple docstring'''






      UpperCamelCase__			:   List[Any]       				=  len(get_test_nested_examples()						)
      with tempfile.TemporaryDirectory() as tmp_cache_dir:
           UpperCamelCase__			:   Any       				=  NestedBeamDataset(cache_dir=SCREAMING_SNAKE_CASE							,   beam_runner="DirectRunner"						)
           builder.download_and_prepare()
           self.assertTrue(
               os.path.exists(
                   os.path.join(SCREAMING_SNAKE_CASE							,   builder.name							,   "default"							,   "0.0.0"							,   F'{builder.name}-train.arrow'						)						)						)
           self.assertDictEqual(
               builder.info.features							,   datasets.Features({"a": datasets.Sequence({"b": datasets.Value("string"						)}						)}						)						)
           UpperCamelCase__			:   List[Any]       				=  builder.as_dataset()
           self.assertEqual(dset["train"].num_rows							,   SCREAMING_SNAKE_CASE						)
           self.assertEqual(dset["train"].info.splits["train"].num_examples							,   SCREAMING_SNAKE_CASE						)
           self.assertDictEqual(dset["train"][0]							,   get_test_nested_examples()[0][1]						)
           self.assertDictEqual(
               dset["train"][expected_num_examples - 1]							,   get_test_nested_examples()[expected_num_examples - 1][1]						)
           self.assertTrue(
               os.path.exists(os.path.join(SCREAMING_SNAKE_CASE							,   builder.name							,   "default"							,   "0.0.0"							,   "dataset_info.json"						)						)						)
           del dset