





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      _SCREAMING_SNAKE_CASE		(			__SCREAMING_SNAKE_CASE					):







 '''simple docstring'''

 def __init__(self       :     List[Any] ,				**UpperCAmelCase_       :     Optional[int]) ->Optional[int]:



   '''simple docstring'''



   requires_backends(self ,				["bs4"])
   super().__init__(**UpperCAmelCase_)

 def 							SCREAMING_SNAKE_CASE_      (self       :     str ,				UpperCAmelCase_       :     Tuple) ->List[str]:



   '''simple docstring'''



   lowerCamelCase__:   List[Any]    						=[]
   lowerCamelCase__:   Tuple    						=[]
   lowerCamelCase__:   Optional[Any]    						=element if element.name else element.parent
   for parent in child.parents:  # type: bs4.element.Tag
     lowerCamelCase__:   Tuple    						=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))
     lowerCamelCase__:   str    						=parent
   xpath_tags.reverse()
   xpath_subscripts.reverse()
   return xpath_tags, xpath_subscripts

 def 							SCREAMING_SNAKE_CASE_      (self       :     List[Any] ,				UpperCAmelCase_       :     int) ->str:



   '''simple docstring'''



   lowerCamelCase__:   Dict    						=BeautifulSoup(UpperCAmelCase_ ,				"html.parser")

   lowerCamelCase__:   Dict    						=[]
   lowerCamelCase__:   Dict    						=[]
   lowerCamelCase__:   Union[str, Any]    						=[]

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

       lowerCamelCase__:   Union[str, Any]    						=html.unescape(UpperCAmelCase_).strip()
       if not text_in_this_tag:
         continue

       all_doc_strings.append(UpperCAmelCase_)

       lowerCamelCase__:   Optional[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 							SCREAMING_SNAKE_CASE_      (self       :     int ,				UpperCAmelCase_       :     int ,				UpperCAmelCase_       :     Tuple) ->Any:



   '''simple docstring'''



   lowerCamelCase__:   Dict    						=""
   for tagname, subs in zip(UpperCAmelCase_ ,				UpperCAmelCase_):
     xpath += F"""/{tagname}"""
     if subs != 0:
       xpath += F"""[{subs}]"""
   return xpath







 def __call__(self       :     List[Any] ,				UpperCAmelCase_       :     Optional[int]) ->BatchFeature:



   '''simple docstring'''



   lowerCamelCase__:   Dict    						=False

   # Check that strings has a valid type
   if isinstance(UpperCAmelCase_ ,				UpperCAmelCase_):
     lowerCamelCase__:   int    						=True
   elif isinstance(UpperCAmelCase_ ,				(list, tuple)):
     if len(UpperCAmelCase_) == 0 or isinstance(html_strings[0] ,				UpperCAmelCase_):
       lowerCamelCase__:   Union[str, 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_)}.""")

   lowerCamelCase__:   Union[str, Any]    						=bool(isinstance(UpperCAmelCase_ ,				(list, tuple)) and (isinstance(html_strings[0] ,				UpperCAmelCase_)))

   if not is_batched:
     lowerCamelCase__:   Dict    						=[html_strings]

   # Get nodes + xpaths
   lowerCamelCase__:   Optional[int]    						=[]
   lowerCamelCase__:   Union[str, Any]    						=[]
   for html_string in html_strings:
     lowerCamelCase__:   Dict    						=self.get_three_from_single(UpperCAmelCase_)
     nodes.append(UpperCAmelCase_)
     lowerCamelCase__:   Optional[Any]    						=[]
     for node, tag_list, sub_list in zip(UpperCAmelCase_ ,				UpperCAmelCase_ ,				UpperCAmelCase_):
       lowerCamelCase__:   int    						=self.construct_xpath(UpperCAmelCase_ ,				UpperCAmelCase_)
       xpath_strings.append(UpperCAmelCase_)
     xpaths.append(UpperCAmelCase_)

   # return as Dict
   lowerCamelCase__:   List[str]    						={"nodes": nodes, "xpaths": xpaths}
   lowerCamelCase__:   List[str]    						=BatchFeature(data=UpperCAmelCase_ ,				tensor_type=UpperCAmelCase_)

   return encoded_inputs








import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
from ...utils import logging
from ..auto import CONFIG_MAPPING


__A             =       logging.get_logger(__name__)

__A             =       {
    "salesforce/blip2-opt-2.7b": "https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json",
}



class      _SCREAMING_SNAKE_CASE		(			__SCREAMING_SNAKE_CASE					):







 '''simple docstring'''
 lowercase_	=    "blip_2_vision_model"

 def __init__(self       :     Union[str, Any] ,				UpperCAmelCase_       :     int=1_408 ,				UpperCAmelCase_       :     List[str]=6_144 ,				UpperCAmelCase_       :     List[Any]=39 ,				UpperCAmelCase_       :     Tuple=16 ,				UpperCAmelCase_       :     List[str]=224 ,				UpperCAmelCase_       :     Any=14 ,				UpperCAmelCase_       :     Dict="gelu" ,				UpperCAmelCase_       :     str=0.0_0001 ,				UpperCAmelCase_       :     List[str]=0.0 ,				UpperCAmelCase_       :     str=1E-1_0 ,				UpperCAmelCase_       :     Any=True ,				**UpperCAmelCase_       :     Optional[Any] ,				) ->Optional[int]:



   '''simple docstring'''



   super().__init__(**UpperCAmelCase_)

   lowerCamelCase__:   Any    						=hidden_size
   lowerCamelCase__:   Any    						=intermediate_size
   lowerCamelCase__:   Union[str, Any]    						=num_hidden_layers
   lowerCamelCase__:   Optional[Any]    						=num_attention_heads
   lowerCamelCase__:   Dict    						=patch_size
   lowerCamelCase__:   List[Any]    						=image_size
   lowerCamelCase__:   Union[str, Any]    						=initializer_range
   lowerCamelCase__:   Optional[Any]    						=attention_dropout
   lowerCamelCase__:   Union[str, Any]    						=layer_norm_eps
   lowerCamelCase__:   Dict    						=hidden_act
   lowerCamelCase__:   Union[str, Any]    						=qkv_bias







 @classmethod
 def 							SCREAMING_SNAKE_CASE_      (cls       :     Optional[int] ,				UpperCAmelCase_       :     Union[str, os.PathLike] ,				**UpperCAmelCase_       :     List[Any]) ->"PretrainedConfig":



   '''simple docstring'''



   cls._set_token_in_kwargs(UpperCAmelCase_)

   lowerCamelCase__						,      lowerCamelCase__:   str    						=cls.get_config_dict(UpperCAmelCase_ ,				**UpperCAmelCase_)

   # get the vision config dict if we are loading from Blip2Config
   if config_dict.get("model_type") == "blip-2":
     lowerCamelCase__:   Any    						=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      _SCREAMING_SNAKE_CASE		(			__SCREAMING_SNAKE_CASE					):







 '''simple docstring'''
 lowercase_	=    "blip_2_qformer"

 def __init__(self       :     str ,				UpperCAmelCase_       :     Any=30_522 ,				UpperCAmelCase_       :     Union[str, Any]=768 ,				UpperCAmelCase_       :     Tuple=12 ,				UpperCAmelCase_       :     Union[str, Any]=12 ,				UpperCAmelCase_       :     Optional[int]=3_072 ,				UpperCAmelCase_       :     Any="gelu" ,				UpperCAmelCase_       :     Optional[int]=0.1 ,				UpperCAmelCase_       :     List[Any]=0.1 ,				UpperCAmelCase_       :     Optional[int]=512 ,				UpperCAmelCase_       :     List[Any]=0.02 ,				UpperCAmelCase_       :     Optional[Any]=1E-1_2 ,				UpperCAmelCase_       :     Dict=0 ,				UpperCAmelCase_       :     Optional[int]="absolute" ,				UpperCAmelCase_       :     List[Any]=2 ,				UpperCAmelCase_       :     int=1_408 ,				**UpperCAmelCase_       :     Optional[int] ,				) ->List[str]:



   '''simple docstring'''



   super().__init__(pad_token_id=UpperCAmelCase_ ,				**UpperCAmelCase_)

   lowerCamelCase__:   Optional[int]    						=vocab_size
   lowerCamelCase__:   Dict    						=hidden_size
   lowerCamelCase__:   Tuple    						=num_hidden_layers
   lowerCamelCase__:   List[Any]    						=num_attention_heads
   lowerCamelCase__:   Optional[Any]    						=hidden_act
   lowerCamelCase__:   Optional[Any]    						=intermediate_size
   lowerCamelCase__:   Dict    						=hidden_dropout_prob
   lowerCamelCase__:   Any    						=attention_probs_dropout_prob
   lowerCamelCase__:   Union[str, Any]    						=max_position_embeddings
   lowerCamelCase__:   Optional[Any]    						=initializer_range
   lowerCamelCase__:   List[Any]    						=layer_norm_eps
   lowerCamelCase__:   Tuple    						=position_embedding_type
   lowerCamelCase__:   List[Any]    						=cross_attention_frequency
   lowerCamelCase__:   Tuple    						=encoder_hidden_size







 @classmethod
 def 							SCREAMING_SNAKE_CASE_      (cls       :     Union[str, Any] ,				UpperCAmelCase_       :     Union[str, os.PathLike] ,				**UpperCAmelCase_       :     List[Any]) ->"PretrainedConfig":



   '''simple docstring'''



   cls._set_token_in_kwargs(UpperCAmelCase_)

   lowerCamelCase__						,      lowerCamelCase__:   Tuple    						=cls.get_config_dict(UpperCAmelCase_ ,				**UpperCAmelCase_)

   # get the qformer config dict if we are loading from Blip2Config
   if config_dict.get("model_type") == "blip-2":
     lowerCamelCase__:   Any    						=config_dict["qformer_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      _SCREAMING_SNAKE_CASE		(			__SCREAMING_SNAKE_CASE					):







 '''simple docstring'''
 lowercase_	=    "blip-2"
 lowercase_	=    True

 def __init__(self       :     Any ,				UpperCAmelCase_       :     Optional[int]=None ,				UpperCAmelCase_       :     Tuple=None ,				UpperCAmelCase_       :     List[str]=None ,				UpperCAmelCase_       :     int=32 ,				**UpperCAmelCase_       :     str) ->List[str]:



   '''simple docstring'''



   super().__init__(**UpperCAmelCase_)

   if vision_config is None:
     lowerCamelCase__:   Optional[int]    						={}
     logger.info("vision_config is None. initializing the Blip2VisionConfig with default values.")

   if qformer_config is None:
     lowerCamelCase__:   str    						={}
     logger.info("qformer_config is None. Initializing the Blip2QFormerConfig with default values.")

   if text_config is None:
     lowerCamelCase__:   Union[str, Any]    						={}
     logger.info("text_config is None. Initializing the text config with default values (`OPTConfig`).")

   lowerCamelCase__:   Optional[Any]    						=BlipaVisionConfig(**UpperCAmelCase_)
   lowerCamelCase__:   Optional[int]    						=BlipaQFormerConfig(**UpperCAmelCase_)
   lowerCamelCase__:   Union[str, Any]    						=text_config["model_type"] if "model_type" in text_config else "opt"
   lowerCamelCase__:   Dict    						=CONFIG_MAPPING[text_model_type](**UpperCAmelCase_)

   lowerCamelCase__:   Optional[int]    						=self.text_config.tie_word_embeddings
   lowerCamelCase__:   List[str]    						=self.text_config.is_encoder_decoder

   lowerCamelCase__:   Dict    						=num_query_tokens
   lowerCamelCase__:   Optional[Any]    						=self.vision_config.hidden_size
   lowerCamelCase__:   Tuple    						=self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
   lowerCamelCase__:   List[Any]    						=1.0
   lowerCamelCase__:   Union[str, Any]    						=0.02

 @classmethod
 def 							SCREAMING_SNAKE_CASE_      (cls       :     Any ,				UpperCAmelCase_       :     BlipaVisionConfig ,				UpperCAmelCase_       :     BlipaQFormerConfig ,				UpperCAmelCase_       :     PretrainedConfig ,				**UpperCAmelCase_       :     int ,				) ->Optional[int]:



   '''simple docstring'''



   return cls(
       vision_config=vision_config.to_dict() ,				qformer_config=qformer_config.to_dict() ,				text_config=text_config.to_dict() ,				**UpperCAmelCase_ ,				)







 def 							SCREAMING_SNAKE_CASE_      (self       :     List[str]) ->int:



   '''simple docstring'''



   lowerCamelCase__:   List[Any]    						=copy.deepcopy(self.__dict__)
   lowerCamelCase__:   Any    						=self.vision_config.to_dict()
   lowerCamelCase__:   Any    						=self.qformer_config.to_dict()
   lowerCamelCase__:   Any    						=self.text_config.to_dict()
   lowerCamelCase__:   int    						=self.__class__.model_type
   return output

