
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		,     _snake_case		,     _snake_case=12		,     _snake_case=7		,     _snake_case=True		,     _snake_case=True		,     _snake_case=True		,     _snake_case=99		,     _snake_case=32		,     _snake_case=32		,     _snake_case=2		,     _snake_case=4		,     _snake_case=37		,     _snake_case=0.1		,     _snake_case=0.1		,     _snake_case=512		,     _snake_case=0.02		,     _snake_case=0		,     _snake_case=None		,     )    ->      Dict:


								'''simple docstring'''




								__a										=    parent
								__a										=    batch_size
								__a										=    seq_length
								__a										=    is_training
								__a										=    use_input_mask
								__a										=    use_labels
								__a										=    vocab_size
								__a										=    hidden_size
								__a										=    projection_dim
								__a										=    num_hidden_layers
								__a										=    num_attention_heads
								__a										=    intermediate_size
								__a										=    dropout
								__a										=    attention_dropout
								__a										=    max_position_embeddings
								__a										=    initializer_range
								__a										=    scope
								__a										=    bos_token_id




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


								'''simple docstring'''




								__a										=    ids_tensor([self.batch_size, self.seq_length]		,     self.vocab_size				)

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

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

								__a										=    self.get_config()

								return config, input_ids, tf.convert_to_tensor(_snake_case				)




				def 				SCREAMING_SNAKE_CASE_		(     self				)    ->      Any:


								'''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 				SCREAMING_SNAKE_CASE_		(     self		,     _snake_case		,     _snake_case		,     _snake_case				)    ->      Optional[Any]:


								'''simple docstring'''




								__a										=    TFBlipTextModel(config=_snake_case				)
								__a										=    model(_snake_case		,     attention_mask=_snake_case		,     training=_snake_case				)
								__a										=    model(_snake_case		,     training=_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 				SCREAMING_SNAKE_CASE_		(     self				)    ->      Dict:


								'''simple docstring'''




								__a										=    self.prepare_config_and_inputs()
								__a							,     __a							,     __a										=    config_and_inputs
								__a										=    {'''input_ids''': input_ids, '''attention_mask''': input_mask}
								return config, inputs_dict







@require_tf
class 			__A( a  ,   unittest.TestCase			):
				snake_case_						   =    (TFBlipTextModel,) if is_tf_available() else ()
				snake_case_						   =    False
				snake_case_						   =    False
				snake_case_						   =    False




				def 				SCREAMING_SNAKE_CASE_		(     self				)    ->      Optional[int]:


								'''simple docstring'''




								__a										=    BlipTextModelTester(self				)
								__a										=    ConfigTester(self		,     config_class=_snake_case		,     hidden_size=37				)




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


								'''simple docstring'''




								self.config_tester.run_common_tests()




				def 				SCREAMING_SNAKE_CASE_		(     self				)    ->      Tuple:


								'''simple docstring'''




								__a										=    self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*_snake_case				)




				def 				SCREAMING_SNAKE_CASE_		(     self				)    ->      str:


								'''simple docstring'''




								pass




				def 				SCREAMING_SNAKE_CASE_		(     self				)    ->      Optional[Any]:


								'''simple docstring'''




								pass




				@unittest.skip(reason='''Blip does not use inputs_embeds'''				)
				def 				SCREAMING_SNAKE_CASE_		(     self				)    ->      Dict:


								'''simple docstring'''




								pass




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


								'''simple docstring'''




								pass




				@unittest.skip(reason='''BlipTextModel has no base class and is not available in MODEL_MAPPING'''				)
				def 				SCREAMING_SNAKE_CASE_		(     self				)    ->      Dict:


								'''simple docstring'''




								pass




				@slow
				def 				SCREAMING_SNAKE_CASE_		(     self				)    ->      str:


								'''simple docstring'''




								for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												__a										=    TFBlipTextModel.from_pretrained(_snake_case				)
												self.assertIsNotNone(_snake_case				)




				def 				SCREAMING_SNAKE_CASE_		(     self		,     _snake_case=True				)    ->      Optional[Any]:


								'''simple docstring'''




								super().test_pt_tf_model_equivalence(allow_missing_keys=_snake_case				)

import html

from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin
from ...utils import is_bsa_available, logging, requires_backends


if is_bsa_available():
					import bsa
					from bsa import BeautifulSoup


A     :	str    = logging.get_logger(__name__)







class 			__A( a			):




				def __init__(     self		,     **_snake_case				)    ->      List[Any]:


								'''simple docstring'''




								requires_backends(self		,     ['''bs4''']				)
								super().__init__(**_snake_case				)




				def 				SCREAMING_SNAKE_CASE_		(     self		,     _snake_case				)    ->      int:


								'''simple docstring'''




								__a										=    []
								__a										=    []
								__a										=    element if element.name else element.parent
								for parent in child.parents:  # type: bs4.element.Tag
												__a										=    parent.find_all(child.name		,     recursive=_snake_case				)
												xpath_tags.append(child.name				)
												xpath_subscripts.append(
												    0 if 1 == len(_snake_case				) else next(i for i, s in enumerate(_snake_case		,     1				) if s is child				)				)
												__a										=    parent
								xpath_tags.reverse()
								xpath_subscripts.reverse()
								return xpath_tags, xpath_subscripts




				def 				SCREAMING_SNAKE_CASE_		(     self		,     _snake_case				)    ->      Optional[int]:


								'''simple docstring'''




								__a										=    BeautifulSoup(_snake_case		,     '''html.parser'''				)

								__a										=    []
								__a										=    []
								__a										=    []

								for element in html_code.descendants:
												if type(_snake_case				) == bsa.element.NavigableString:
																if type(element.parent				) != bsa.element.Tag:
																				continue

																__a										=    html.unescape(_snake_case				).strip()
																if not text_in_this_tag:
																				continue

																all_doc_strings.append(_snake_case				)

																__a							,     __a										=    self.xpath_soup(_snake_case				)
																stringaxtag_seq.append(_snake_case				)
																stringaxsubs_seq.append(_snake_case				)

								if len(_snake_case				) != len(_snake_case				):
												raise ValueError('''Number of doc strings and xtags does not correspond'''				)
								if len(_snake_case				) != len(_snake_case				):
												raise ValueError('''Number of doc strings and xsubs does not correspond'''				)

								return all_doc_strings, stringaxtag_seq, stringaxsubs_seq




				def 				SCREAMING_SNAKE_CASE_		(     self		,     _snake_case		,     _snake_case				)    ->      Optional[int]:


								'''simple docstring'''




								__a										=    ''''''
								for tagname, subs in zip(_snake_case		,     _snake_case				):
												xpath += F"""/{tagname}"""
												if subs != 0:
																xpath += F"""[{subs}]"""
								return xpath




				def __call__(     self		,     _snake_case				)    ->      BatchFeature:


								'''simple docstring'''




								__a										=    False

								# Check that strings has a valid type
								if isinstance(_snake_case		,     _snake_case				):
												__a										=    True
								elif isinstance(_snake_case		,     (list, tuple)				):
												if len(_snake_case				) == 0 or isinstance(html_strings[0]		,     _snake_case				):
																__a										=    True

								if not valid_strings:
												raise ValueError(
												    '''HTML strings must of type `str`, `List[str]` (batch of examples), '''
												    F"""but is of type {type(_snake_case				)}."""				)

								__a										=    bool(isinstance(_snake_case		,     (list, tuple)				) and (isinstance(html_strings[0]		,     _snake_case				))				)

								if not is_batched:
												__a										=    [html_strings]

								# Get nodes + xpaths
								__a										=    []
								__a										=    []
								for html_string in html_strings:
												__a							,     __a							,     __a										=    self.get_three_from_single(_snake_case				)
												nodes.append(_snake_case				)
												__a										=    []
												for node, tag_list, sub_list in zip(_snake_case		,     _snake_case		,     _snake_case				):
																__a										=    self.construct_xpath(_snake_case		,     _snake_case				)
																xpath_strings.append(_snake_case				)
												xpaths.append(_snake_case				)

								# return as Dict
								__a										=    {'''nodes''': nodes, '''xpaths''': xpaths}
								__a										=    BatchFeature(data=_snake_case		,     tensor_type=_snake_case				)

								return encoded_inputs