

"""simple docstring"""






from __future__ import annotations

import unittest

from transformers import XGLMConfig, XGLMTokenizer, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
 import tensorflow as tf

 from transformers.models.xglm.modeling_tf_xglm import (
     TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST,
     TFXGLMForCausalLM,
     TFXGLMModel,
 )
@require_tf
class        _lowercase					:
     _lowerCamelCase     =       XGLMConfig
     _lowerCamelCase     =       {}
     _lowerCamelCase     =       "gelu"







     def __init__(      self ,						UpperCamelCase_ ,						UpperCamelCase_=14 ,						UpperCamelCase_=7 ,						UpperCamelCase_=True ,						UpperCamelCase_=True ,						UpperCamelCase_=True ,						UpperCamelCase_=99 ,						UpperCamelCase_=32 ,						UpperCamelCase_=2 ,						UpperCamelCase_=4 ,						UpperCamelCase_=37 ,						UpperCamelCase_="gelu" ,						UpperCamelCase_=0.1 ,						UpperCamelCase_=0.1 ,						UpperCamelCase_=512 ,						UpperCamelCase_=0.0_2 ,						):
      __magic_name__     =      parent
      __magic_name__     =      batch_size
      __magic_name__     =      seq_length
      __magic_name__     =      is_training
      __magic_name__     =      use_input_mask
      __magic_name__     =      use_labels
      __magic_name__     =      vocab_size
      __magic_name__     =      d_model
      __magic_name__     =      num_hidden_layers
      __magic_name__     =      num_attention_heads
      __magic_name__     =      ffn_dim
      __magic_name__     =      activation_function
      __magic_name__     =      activation_dropout
      __magic_name__     =      attention_dropout
      __magic_name__     =      max_position_embeddings
      __magic_name__     =      initializer_range
      __magic_name__     =      None
      __magic_name__     =      0
      __magic_name__     =      2
      __magic_name__     =      1







     def 	lowerCAmelCase__    (      self       ):
      return XGLMConfig.from_pretrained('''facebook/xglm-564M'''       )







     def 	lowerCAmelCase__    (      self       ):
      __magic_name__     =      tf.clip_by_value(
          ids_tensor([self.batch_size, self.seq_length] ,						self.vocab_size       ) ,						clip_value_min=0 ,						clip_value_max=3       )

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

      __magic_name__     =      self.get_config()

      __magic_name__     =      floats_tensor([self.num_hidden_layers, self.num_attention_heads] ,						2       )

      return (
          config,
          input_ids,
          input_mask,
          head_mask,
      )







     def 	lowerCAmelCase__    (      self       ):
      return XGLMConfig(
          vocab_size=self.vocab_size ,						d_model=self.hidden_size ,						num_layers=self.num_hidden_layers ,						attention_heads=self.num_attention_heads ,						ffn_dim=self.ffn_dim ,						activation_function=self.activation_function ,						activation_dropout=self.activation_dropout ,						attention_dropout=self.attention_dropout ,						max_position_embeddings=self.max_position_embeddings ,						initializer_range=self.initializer_range ,						use_cache=A_ ,						bos_token_id=self.bos_token_id ,						eos_token_id=self.eos_token_id ,						pad_token_id=self.pad_token_id ,						return_dict=A_ ,						)







     def 	lowerCAmelCase__    (      self       ):
      __magic_name__     =      self.prepare_config_and_inputs()

      (
          (
          __magic_name__						
      )   ,						(
          __magic_name__						
      )   ,						(
          __magic_name__						
      )   ,						(
          __magic_name__						
      )   ,												
      )     =      config_and_inputs

      __magic_name__     =      {
          '''input_ids''': input_ids,
          '''head_mask''': head_mask,
      }

      return config, inputs_dict


@require_tf
class        _lowercase					(     _SCREAMING_SNAKE_CASE   , _SCREAMING_SNAKE_CASE   , unittest.TestCase     ):
     _lowerCamelCase     =       (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else ()
     _lowerCamelCase     =       (TFXGLMForCausalLM,) if is_tf_available() else ()
     _lowerCamelCase     =       (
         {"feature-extraction": TFXGLMModel, "text-generation": TFXGLMForCausalLM} if is_tf_available() else {}
     )
     _lowerCamelCase     =       False
     _lowerCamelCase     =       False
     _lowerCamelCase     =       False







     def 	lowerCAmelCase__    (      self       ):
      __magic_name__     =      TFXGLMModelTester(self       )
      __magic_name__     =      ConfigTester(self ,						config_class=A_ ,						n_embd=37       )







     def 	lowerCAmelCase__    (      self       ):
      self.config_tester.run_common_tests()







     @slow
     def 	lowerCAmelCase__    (      self       ):
      for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       __magic_name__     =      TFXGLMModel.from_pretrained(A_       )
       self.assertIsNotNone(A_       )







     @unittest.skip(reason='''Currently, model embeddings are going to undergo a major refactor.'''       )
     def 	lowerCAmelCase__    (      self       ):
      super().test_resize_token_embeddings()


@require_tf
class        _lowercase					(     unittest.TestCase     ):







     @slow
     def 	lowerCAmelCase__    (      self ,						UpperCamelCase_=True       ):
      __magic_name__     =      TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M'''       )
      __magic_name__     =      tf.convert_to_tensor([[2, 268, 9865]] ,						dtype=tf.intaa       )  # The dog
      # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other
      # fmt: off
      __magic_name__     =      [2, 268, 9865, 67, 11, 1988, 5_7252, 9865, 5, 984, 67, 1988, 21_3838, 1658, 53, 7_0446, 33, 6657, 278, 1581]
      # fmt: on
      __magic_name__     =      model.generate(A_ ,						do_sample=A_ ,						num_beams=1       )
      if verify_outputs:
       self.assertListEqual(output_ids[0].numpy().tolist() ,						A_       )







     @slow
     def 	lowerCAmelCase__    (      self       ):
      __magic_name__     =      XGLMTokenizer.from_pretrained('''facebook/xglm-564M'''       )
      __magic_name__     =      TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M'''       )

      tf.random.set_seed(0       )
      __magic_name__     =      tokenizer('''Today is a nice day and''' ,						return_tensors='''tf'''       )
      __magic_name__     =      tokenized.input_ids
      # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices)
      with tf.device(''':/CPU:0'''       ):
       __magic_name__     =      model.generate(A_ ,						do_sample=A_ ,						seed=[7, 0]       )
      __magic_name__     =      tokenizer.decode(output_ids[0] ,						skip_special_tokens=A_       )

      __magic_name__     =      (
          '''Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due'''
      )
      self.assertEqual(A_ ,						A_       )







     @slow
     def 	lowerCAmelCase__    (      self       ):
      __magic_name__     =      TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M'''       )
      __magic_name__     =      XGLMTokenizer.from_pretrained('''facebook/xglm-564M'''       )

      __magic_name__     =      '''left'''

      # use different length sentences to test batching
      __magic_name__     =      [
          '''This is an extremelly long sentence that only exists to test the ability of the model to cope with '''
          '''left-padding, such as in batched generation. The output for the sequence below should be the same '''
          '''regardless of whether left padding is applied or not. When''',
          '''Hello, my dog is a little''',
      ]

      __magic_name__     =      tokenizer(A_ ,						return_tensors='''tf''' ,						padding=A_       )
      __magic_name__     =      inputs['''input_ids''']

      __magic_name__     =      model.generate(input_ids=A_ ,						attention_mask=inputs['''attention_mask'''] ,						max_new_tokens=12       )

      __magic_name__     =      tokenizer(sentences[0] ,						return_tensors='''tf'''       ).input_ids
      __magic_name__     =      model.generate(input_ids=A_ ,						max_new_tokens=12       )

      __magic_name__     =      tokenizer(sentences[1] ,						return_tensors='''tf'''       ).input_ids
      __magic_name__     =      model.generate(input_ids=A_ ,						max_new_tokens=12       )

      __magic_name__     =      tokenizer.batch_decode(A_ ,						skip_special_tokens=A_       )
      __magic_name__     =      tokenizer.decode(output_non_padded[0] ,						skip_special_tokens=A_       )
      __magic_name__     =      tokenizer.decode(output_padded[0] ,						skip_special_tokens=A_       )

      __magic_name__     =      [
          '''This is an extremelly long sentence that only exists to test the ability of the model to cope with '''
          '''left-padding, such as in batched generation. The output for the sequence below should be the same '''
          '''regardless of whether left padding is applied or not. When left padding is applied, the sequence will be '''
          '''a single''',
          '''Hello, my dog is a little bit of a shy one, but he is very friendly''',
      ]
      self.assertListEqual(A_ ,						A_       )
      self.assertListEqual(A_ ,						[non_padded_sentence, padded_sentence]       )








"""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


__lowerCamelCase										=		logging.get_logger(__name__)
class        _lowercase					(     __UpperCAmelCase     ):







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







     def 	lowerCAmelCase__    (      self ,						UpperCamelCase_       ):
      __magic_name__     =      []
      __magic_name__     =      []
      __magic_name__     =      element if element.name else element.parent
      for parent in child.parents:  # type: bs4.element.Tag
       __magic_name__     =      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       )       )
       __magic_name__     =      parent
      xpath_tags.reverse()
      xpath_subscripts.reverse()
      return xpath_tags, xpath_subscripts







     def 	lowerCAmelCase__    (      self ,						UpperCamelCase_       ):
      __magic_name__     =      BeautifulSoup(UpperCamelCase_ ,						'''html.parser'''       )

      __magic_name__     =      []
      __magic_name__     =      []
      __magic_name__     =      []

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

        __magic_name__     =      html.unescape(UpperCamelCase_       ).strip()
        if not text_in_this_tag:
         continue

        all_doc_strings.append(UpperCamelCase_       )

        __magic_name__   ,						__magic_name__     =      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_       ):
      __magic_name__     =      ''''''
      for tagname, subs in zip(UpperCamelCase_ ,						UpperCamelCase_       ):
       xpath += f'''/{tagname}'''
       if subs != 0:
        xpath += f'''[{subs}]'''
      return xpath







     def __call__(      self ,						UpperCamelCase_       ):
      __magic_name__     =      False

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

      __magic_name__     =      bool(isinstance(UpperCamelCase_ ,						(list, tuple)       ) and (isinstance(html_strings[0] ,						UpperCamelCase_       ))       )

      if not is_batched:
       __magic_name__     =      [html_strings]

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

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

      return encoded_inputs

