'''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		(						_lowerCamelCase						):







     """simple docstring"""






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







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







     def lowerCAmelCase     (		self     ,			_lowerCamelCase    ):
         __UpperCamelCase	:	List[str]		    =  BeautifulSoup(_lowerCamelCase     ,			'html.parser'    )

         __UpperCamelCase	:	int		    =  []
         __UpperCamelCase	:	List[Any]		    =  []
         __UpperCamelCase	:	int		    =  []

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

                 __UpperCamelCase	:	Tuple		    =  html.unescape(_lowerCamelCase    ).strip()
                 if not text_in_this_tag:
                     continue

                 all_doc_strings.append(_lowerCamelCase    )

                 __UpperCamelCase    ,					__UpperCamelCase	:	Union[str, Any]		    =  self.xpath_soup(_lowerCamelCase    )
                 stringaxtag_seq.append(_lowerCamelCase    )
                 stringaxsubs_seq.append(_lowerCamelCase    )

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

         return all_doc_strings, stringaxtag_seq, stringaxsubs_seq







     def lowerCAmelCase     (		self     ,			_lowerCamelCase     ,			_lowerCamelCase    ):
         __UpperCamelCase	:	Dict		    =  ''
         for tagname, subs in zip(_lowerCamelCase     ,			_lowerCamelCase    ):
             xpath += f"""/{tagname}"""
             if subs != 0:
                 xpath += f"""[{subs}]"""
         return xpath







     def __call__(		self     ,			_lowerCamelCase    ):
         __UpperCamelCase	:	List[Any]		    =  False

         # Check that strings has a valid type
         if isinstance(_lowerCamelCase     ,			_lowerCamelCase    ):
             __UpperCamelCase	:	List[str]		    =  True
         elif isinstance(_lowerCamelCase     ,			(list, tuple)    ):
             if len(_lowerCamelCase    ) == 0 or isinstance(html_strings[0]     ,			_lowerCamelCase    ):
                 __UpperCamelCase	:	Optional[int]		    =  True

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

         __UpperCamelCase	:	Dict		    =  bool(isinstance(_lowerCamelCase     ,			(list, tuple)    ) and (isinstance(html_strings[0]     ,			_lowerCamelCase    ))    )

         if not is_batched:
             __UpperCamelCase	:	Tuple		    =  [html_strings]

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

         # return as Dict
         __UpperCamelCase	:	Optional[int]		    =  {'nodes': nodes, 'xpaths': xpaths}
         __UpperCamelCase	:	Union[str, Any]		    =  BatchFeature(data=_lowerCamelCase     ,			tensor_type=_lowerCamelCase    )

         return encoded_inputs




'''simple docstring'''
import torch
from torch import nn

from ...configuration_utils import ConfigMixin, register_to_config
from ...models import ModelMixin






class 			__lowercase		(						_lowerCamelCase			,							_lowerCamelCase						):







     """simple docstring"""






     @register_to_config
     def __init__(		self     ,			*,
         _lowerCamelCase = 4     ,			_lowerCamelCase = 7_6_8     ,			_lowerCamelCase     ,			_lowerCamelCase     ,			):
         super().__init__()

         __UpperCamelCase	:	Optional[int]		    =  nn.Parameter(torch.zeros(_lowerCamelCase    )    )

         # parameters for additional clip time embeddings
         __UpperCamelCase	:	Dict		    =  nn.Linear(_lowerCamelCase     ,			_lowerCamelCase    )
         __UpperCamelCase	:	int		    =  nn.Linear(_lowerCamelCase     ,			_lowerCamelCase    )

         # parameters for encoder hidden states
         __UpperCamelCase	:	Optional[Any]		    =  clip_extra_context_tokens
         __UpperCamelCase	:	Dict		    =  nn.Linear(
             _lowerCamelCase     ,			self.clip_extra_context_tokens * cross_attention_dim    )
         __UpperCamelCase	:	str		    =  nn.Linear(_lowerCamelCase     ,			_lowerCamelCase    )
         __UpperCamelCase	:	List[str]		    =  nn.LayerNorm(_lowerCamelCase    )







     def lowerCAmelCase     (		self     ,			*, _lowerCamelCase     ,			_lowerCamelCase     ,			_lowerCamelCase     ,			_lowerCamelCase    ):
         if do_classifier_free_guidance:
             # Add the classifier free guidance embeddings to the image embeddings
             __UpperCamelCase	:	int		    =  image_embeddings.shape[0]
             __UpperCamelCase	:	Optional[Any]		    =  self.learned_classifier_free_guidance_embeddings.unsqueeze(0    )
             __UpperCamelCase	:	List[Any]		    =  classifier_free_guidance_embeddings.expand(
                 _lowerCamelCase     ,			-1    )
             __UpperCamelCase	:	Optional[Any]		    =  torch.cat([classifier_free_guidance_embeddings, image_embeddings]     ,			dim=0    )

         # The image embeddings batch size and the text embeddings batch size are equal
         assert image_embeddings.shape[0] == prompt_embeds.shape[0]

         __UpperCamelCase	:	Optional[Any]		    =  prompt_embeds.shape[0]

         # "Specifically, we modify the architecture described in Nichol et al. (2021) by projecting and
         # adding CLIP embeddings to the existing timestep embedding, ...
         __UpperCamelCase	:	Optional[int]		    =  self.embedding_proj(_lowerCamelCase    )
         __UpperCamelCase	:	List[str]		    =  self.clip_image_embeddings_project_to_time_embeddings(_lowerCamelCase    )
         __UpperCamelCase	:	Optional[int]		    =  time_projected_image_embeddings + time_projected_prompt_embeds

         # ... and by projecting CLIP embeddings into four
         # extra tokens of context that are concatenated to the sequence of outputs from the GLIDE text encoder"
         __UpperCamelCase	:	Optional[int]		    =  self.clip_extra_context_tokens_proj(_lowerCamelCase    )
         __UpperCamelCase	:	Tuple		    =  clip_extra_context_tokens.reshape(_lowerCamelCase     ,			-1     ,			self.clip_extra_context_tokens    )
         __UpperCamelCase	:	Dict		    =  clip_extra_context_tokens.permute(0     ,			2     ,			1    )

         __UpperCamelCase	:	Union[str, Any]		    =  self.encoder_hidden_states_proj(_lowerCamelCase    )
         __UpperCamelCase	:	Optional[Any]		    =  self.text_encoder_hidden_states_norm(_lowerCamelCase    )
         __UpperCamelCase	:	Tuple		    =  torch.cat([clip_extra_context_tokens, text_encoder_hidden_states]     ,			dim=1    )

         return text_encoder_hidden_states, additive_clip_time_embeddings



