





import copy
import os
from typing import TYPE_CHECKING, List, Union


if TYPE_CHECKING:
		pass

from ...configuration_utils import PretrainedConfig
from ...utils import logging


A 			=  logging.get_logger(__name__)

A 			=  {
    '''kakaobrain/align-base''': '''https://huggingface.co/kakaobrain/align-base/resolve/main/config.json''',
}




class 				__lowercase			(			_UpperCamelCase							):







					'''simple docstring'''




					__lowerCAmelCase  =  '''align_text_model'''







					def __init__(						self	,			_UpperCAmelCase=30522	,			_UpperCAmelCase=768	,			_UpperCAmelCase=12	,			_UpperCAmelCase=12	,			_UpperCAmelCase=3072	,			_UpperCAmelCase="gelu"	,			_UpperCAmelCase=0.1	,			_UpperCAmelCase=0.1	,			_UpperCAmelCase=512	,			_UpperCAmelCase=2	,			_UpperCAmelCase=0.0_2	,			_UpperCAmelCase=1e-1_2	,			_UpperCAmelCase=0	,			_UpperCAmelCase="absolute"	,			_UpperCAmelCase=True	,			**_UpperCAmelCase	,			):
									super().__init__(**_UpperCAmelCase     )

									__a :						Any			       =  vocab_size
									__a :						Union[str, Any]			       =  hidden_size
									__a :						Optional[Any]			       =  num_hidden_layers
									__a :						str			       =  num_attention_heads
									__a :						Optional[Any]			       =  hidden_act
									__a :						Optional[int]			       =  intermediate_size
									__a :						Any			       =  hidden_dropout_prob
									__a :						Any			       =  attention_probs_dropout_prob
									__a :						Union[str, Any]			       =  max_position_embeddings
									__a :						Tuple			       =  type_vocab_size
									__a :						Dict			       =  initializer_range
									__a :						str			       =  layer_norm_eps
									__a :						List[Any]			       =  position_embedding_type
									__a :						Optional[Any]			       =  use_cache
									__a :						Any			       =  pad_token_id







					@classmethod
					def  _lowerCamelCase		(						cls	,			_UpperCAmelCase	,			**_UpperCAmelCase     ):
									cls._set_token_in_kwargs(_UpperCAmelCase     )

									__a :						Any			       =  cls.get_config_dict(_UpperCAmelCase	,			**_UpperCAmelCase     )

									# get the text config dict if we are loading from AlignConfig
									if config_dict.get('''model_type'''     ) == "align":
													__a :						Any			       =  config_dict['''text_config''']

									if "model_type" in config_dict and hasattr(cls	,			'''model_type'''     ) and config_dict["model_type"] != cls.model_type:
													logger.warning(
													    f"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """
													    f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""     )

									return cls.from_dict(_UpperCAmelCase	,			**_UpperCAmelCase     )






class 				__lowercase			(			_UpperCamelCase							):







					'''simple docstring'''




					__lowerCAmelCase  =  '''align_vision_model'''







					def __init__(						self	,			_UpperCAmelCase = 3	,			_UpperCAmelCase = 600	,			_UpperCAmelCase = 2.0	,			_UpperCAmelCase = 3.1	,			_UpperCAmelCase = 8	,			_UpperCAmelCase = [3, 3, 5, 3, 5, 5, 3]	,			_UpperCAmelCase = [32, 16, 24, 40, 80, 112, 192]	,			_UpperCAmelCase = [16, 24, 40, 80, 112, 192, 320]	,			_UpperCAmelCase = []	,			_UpperCAmelCase = [1, 2, 2, 2, 1, 2, 1]	,			_UpperCAmelCase = [1, 2, 2, 3, 3, 4, 1]	,			_UpperCAmelCase = [1, 6, 6, 6, 6, 6, 6]	,			_UpperCAmelCase = 0.2_5	,			_UpperCAmelCase = "swish"	,			_UpperCAmelCase = 2560	,			_UpperCAmelCase = "mean"	,			_UpperCAmelCase = 0.0_2	,			_UpperCAmelCase = 0.0_0_1	,			_UpperCAmelCase = 0.9_9	,			_UpperCAmelCase = 0.2	,			**_UpperCAmelCase	,			):
									super().__init__(**_UpperCAmelCase     )

									__a :						Dict			       =  num_channels
									__a :						Dict			       =  image_size
									__a :						List[Any]			       =  width_coefficient
									__a :						Optional[int]			       =  depth_coefficient
									__a :						Optional[int]			       =  depth_divisor
									__a :						Any			       =  kernel_sizes
									__a :						List[str]			       =  in_channels
									__a :						Optional[Any]			       =  out_channels
									__a :						Union[str, Any]			       =  depthwise_padding
									__a :						Dict			       =  strides
									__a :						Union[str, Any]			       =  num_block_repeats
									__a :						Optional[Any]			       =  expand_ratios
									__a :						str			       =  squeeze_expansion_ratio
									__a :						Dict			       =  hidden_act
									__a :						List[Any]			       =  hidden_dim
									__a :						Optional[int]			       =  pooling_type
									__a :						Tuple			       =  initializer_range
									__a :						Dict			       =  batch_norm_eps
									__a :						Dict			       =  batch_norm_momentum
									__a :						Dict			       =  drop_connect_rate
									__a :						int			       =  sum(_UpperCAmelCase     ) * 4







					@classmethod
					def  _lowerCamelCase		(						cls	,			_UpperCAmelCase	,			**_UpperCAmelCase     ):
									cls._set_token_in_kwargs(_UpperCAmelCase     )

									__a :						int			       =  cls.get_config_dict(_UpperCAmelCase	,			**_UpperCAmelCase     )

									# get the vision config dict if we are loading from AlignConfig
									if config_dict.get('''model_type'''     ) == "align":
													__a :						Optional[int]			       =  config_dict['''vision_config''']

									if "model_type" in config_dict and hasattr(cls	,			'''model_type'''     ) and config_dict["model_type"] != cls.model_type:
													logger.warning(
													    f"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """
													    f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""     )

									return cls.from_dict(_UpperCAmelCase	,			**_UpperCAmelCase     )






class 				__lowercase			(			_UpperCamelCase							):







					'''simple docstring'''




					__lowerCAmelCase  =  '''align'''
					__lowerCAmelCase  =  True







					def __init__(						self	,			_UpperCAmelCase=None	,			_UpperCAmelCase=None	,			_UpperCAmelCase=640	,			_UpperCAmelCase=1.0	,			_UpperCAmelCase=0.0_2	,			**_UpperCAmelCase	,			):
									super().__init__(**_UpperCAmelCase     )

									if text_config is None:
													__a :						List[str]			       =  {}
													logger.info('''text_config is None. Initializing the AlignTextConfig with default values.'''     )

									if vision_config is None:
													__a :						Tuple			       =  {}
													logger.info('''vision_config is None. Initializing the AlignVisionConfig with default values.'''     )

									__a :						Union[str, Any]			       =  AlignTextConfig(**_UpperCAmelCase     )
									__a :						Any			       =  AlignVisionConfig(**_UpperCAmelCase     )

									__a :						int			       =  projection_dim
									__a :						Union[str, Any]			       =  temperature_init_value
									__a :						Dict			       =  initializer_range







					@classmethod
					def  _lowerCamelCase		(						cls	,			_UpperCAmelCase	,			_UpperCAmelCase	,			**_UpperCAmelCase     ):
									return cls(text_config=text_config.to_dict()	,			vision_config=vision_config.to_dict()	,			**_UpperCAmelCase     )







					def  _lowerCamelCase		(						self     ):
									__a :						Any			       =  copy.deepcopy(self.__dict__     )
									__a :						str			       =  self.text_config.to_dict()
									__a :						List[str]			       =  self.vision_config.to_dict()
									__a :						List[Any]			       =  self.__class__.model_type
									return output






"""simple docstring"""






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 			=  logging.get_logger(__name__)




class 				__lowercase			(			_UpperCamelCase							):







					'''simple docstring'''




					def __init__(						self	,			**_UpperCAmelCase     ):
									requires_backends(self	,			['''bs4''']     )
									super().__init__(**_UpperCAmelCase     )







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







					def  _lowerCamelCase		(						self	,			_UpperCAmelCase     ):
									__a :						Dict			       =  BeautifulSoup(_UpperCAmelCase	,			'''html.parser'''     )

									__a :						Any			       =  []
									__a :						Dict			       =  []
									__a :						Optional[int]			       =  []

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

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

																	all_doc_strings.append(_UpperCAmelCase     )

																	__a       ,						__a :						List[Any]			       =  self.xpath_soup(_UpperCAmelCase     )
																	stringaxtag_seq.append(_UpperCAmelCase     )
																	stringaxsubs_seq.append(_UpperCAmelCase     )

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

									return all_doc_strings, stringaxtag_seq, stringaxsubs_seq







					def  _lowerCamelCase		(						self	,			_UpperCAmelCase	,			_UpperCAmelCase     ):
									__a :						List[str]			       =  ''''''
									for tagname, subs in zip(_UpperCAmelCase	,			_UpperCAmelCase     ):
													xpath += f"""/{tagname}"""
													if subs != 0:
																	xpath += f"""[{subs}]"""
									return xpath







					def __call__(						self	,			_UpperCAmelCase     ):
									__a :						Optional[Any]			       =  False

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

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

									__a :						List[str]			       =  bool(isinstance(_UpperCAmelCase	,			(list, tuple)     ) and (isinstance(html_strings[0]	,			_UpperCAmelCase     ))     )

									if not is_batched:
													__a :						List[Any]			       =  [html_strings]

									# Get nodes + xpaths
									__a :						Tuple			       =  []
									__a :						int			       =  []
									for html_string in html_strings:
													__a       ,						__a       ,						__a :						Any			       =  self.get_three_from_single(_UpperCAmelCase     )
													nodes.append(_UpperCAmelCase     )
													__a :						List[Any]			       =  []
													for node, tag_list, sub_list in zip(_UpperCAmelCase	,			_UpperCAmelCase	,			_UpperCAmelCase     ):
																	__a :						Optional[int]			       =  self.construct_xpath(_UpperCAmelCase	,			_UpperCAmelCase     )
																	xpath_strings.append(_UpperCAmelCase     )
													xpaths.append(_UpperCAmelCase     )

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

									return encoded_inputs