




import unittest

from transformers.testing_utils import require_bsa
from transformers.utils import is_bsa_available

from ...test_feature_extraction_common import FeatureExtractionSavingTestMixin


if is_bsa_available():
     from transformers import MarkupLMFeatureExtractor

class   __a(					unittest.TestCase       ):






    """simple docstring"""





    def __init__(				self       ,_SCREAMING_SNAKE_CASE  )			->		Dict:
         UpperCAmelCase_      :							str       =      parent





    def 							a__				(				self  )			->		Optional[Any]:
         return {}





def lowerCamelCase__       (      ):

     '''simple docstring'''


     UpperCAmelCase_      :							Union[str, Any]       =      '''<HTML>\n\n    <HEAD>\n    <TITLE>sample document</TITLE>\n    </HEAD>\n\n    <BODY BGCOLOR="FFFFFF">\n    <HR>\n    <a href="http://google.com">Goog</a>\n    <H1>This is one header</H1>\n    <H2>This is a another Header</H2>\n    <P>Travel from\n        <P>\n        <B>SFO to JFK</B>\n        <BR>\n        <B><I>on May 2, 2015 at 2:00 pm. For details go to confirm.com </I></B>\n        <HR>\n        <div style="color:#0000FF">\n            <h3>Traveler <b> name </b> is\n            <p> John Doe </p>\n        </div>'''

     UpperCAmelCase_      :							Optional[Any]       =      '''\n    <!DOCTYPE html>\n    <html>\n    <body>\n\n    <h1>My First Heading</h1>\n    <p>My first paragraph.</p>\n\n    </body>\n    </html>\n    '''

     return [html_string_a, html_string_a]



@require_bsa
class   __a(					__lowercase    ,						unittest.TestCase       ):






    """simple docstring"""





    lowerCAmelCase        =				MarkupLMFeatureExtractor if is_bsa_available() else None





    def 							a__				(				self  )			->		List[str]:
         UpperCAmelCase_      :							Optional[Any]       =      MarkupLMFeatureExtractionTester(self  )





    @property
    def 							a__				(				self  )			->		Union[str, Any]:
         return self.feature_extract_tester.prepare_feat_extract_dict()





    def 							a__				(				self  )			->		List[str]:
         # Initialize feature_extractor
         UpperCAmelCase_      :							Optional[int]       =      self.feature_extraction_class()

         # Test not batched input
         UpperCAmelCase_      :							Optional[Any]       =      get_html_strings()[0]
         UpperCAmelCase_      :							Optional[int]       =      feature_extractor(UpperCAmelCase__  )

         # fmt: off
         UpperCAmelCase_      :							List[Any]       =      [['''sample document''', '''Goog''', '''This is one header''', '''This is a another Header''', '''Travel from''', '''SFO to JFK''', '''on May 2, 2015 at 2:00 pm. For details go to confirm.com''', '''Traveler''', '''name''', '''is''', '''John Doe''']]
         UpperCAmelCase_      :							Dict       =      [['''/html/head/title''', '''/html/body/a''', '''/html/body/h1''', '''/html/body/h2''', '''/html/body/p''', '''/html/body/p/p/b[1]''', '''/html/body/p/p/b[2]/i''', '''/html/body/p/p/div/h3''', '''/html/body/p/p/div/h3/b''', '''/html/body/p/p/div/h3''', '''/html/body/p/p/div/h3/p''']]
         # fmt: on

         self.assertEqual(encoding.nodes       ,UpperCAmelCase__  )
         self.assertEqual(encoding.xpaths       ,UpperCAmelCase__  )

         # Test batched
         UpperCAmelCase_      :							Union[str, Any]       =      get_html_strings()
         UpperCAmelCase_      :							List[Any]       =      feature_extractor(UpperCAmelCase__  )

         # fmt: off
         UpperCAmelCase_      :							Tuple       =      expected_nodes + [['''My First Heading''', '''My first paragraph.''']]
         UpperCAmelCase_      :							Tuple       =      expected_xpaths + [['''/html/body/h1''', '''/html/body/p''']]

         self.assertEqual(len(encoding.nodes  )       ,2  )
         self.assertEqual(len(encoding.xpaths  )       ,2  )

         self.assertEqual(encoding.nodes       ,UpperCAmelCase__  )
         self.assertEqual(encoding.xpaths       ,UpperCAmelCase__  )





from random import shuffle

import tensorflow as tf
from numpy import array







def lowerCamelCase__       (      _lowercase			,						_lowercase				):

     '''simple docstring'''


     UpperCAmelCase_      :							Union[str, Any]       =      int(_lowercase				)
     assert noofclusters < len(_lowercase				)

     # Find out the dimensionality
     UpperCAmelCase_      :							Optional[int]       =      len(vectors[0]				)

     # Will help select random centroids from among the available vectors
     UpperCAmelCase_      :							Optional[int]       =      list(range(len(_lowercase				)				)				)
     shuffle(_lowercase				)

     # GRAPH OF COMPUTATION
     # We initialize a new graph and set it as the default during each run
     # of this algorithm. This ensures that as this function is called
     # multiple times, the default graph doesn't keep getting crowded with
     # unused ops and Variables from previous function calls.

     UpperCAmelCase_      :							List[str]       =      tf.Graph()

     with graph.as_default():
          # SESSION OF COMPUTATION

          UpperCAmelCase_      :							Tuple       =      tf.Session()

          ##CONSTRUCTING THE ELEMENTS OF COMPUTATION

          ##First lets ensure we have a Variable vector for each centroid,
          ##initialized to one of the vectors from the available data points
          UpperCAmelCase_      :							str       =      [
              tf.Variable(vectors[vector_indices[i]]				) for i in range(_lowercase				)
          ]
          ##These nodes will assign the centroid Variables the appropriate
          ##values
          UpperCAmelCase_      :							List[Any]       =      tf.placeholder('''float64'''			,						[dim]				)
          UpperCAmelCase_      :							List[Any]       =      []
          for centroid in centroids:
               cent_assigns.append(tf.assign(_lowercase			,						_lowercase				)				)

          ##Variables for cluster assignments of individual vectors(initialized
          ##to 0 at first)
          UpperCAmelCase_      :							Optional[int]       =      [tf.Variable(0				) for i in range(len(_lowercase				)				)]
          ##These nodes will assign an assignment Variable the appropriate
          ##value
          UpperCAmelCase_      :							List[Any]       =      tf.placeholder('''int32'''				)
          UpperCAmelCase_      :							Union[str, Any]       =      []
          for assignment in assignments:
               cluster_assigns.append(tf.assign(_lowercase			,						_lowercase				)				)

          ##Now lets construct the node that will compute the mean
          # The placeholder for the input
          UpperCAmelCase_      :							Tuple       =      tf.placeholder('''float'''			,						[None, dim]				)
          # The Node/op takes the input and computes a mean along the 0th
          # dimension, i.e. the list of input vectors
          UpperCAmelCase_      :							str       =      tf.reduce_mean(_lowercase			,						0				)

          ##Node for computing Euclidean distances
          # Placeholders for input
          UpperCAmelCase_      :							List[Any]       =      tf.placeholder('''float'''			,						[dim]				)
          UpperCAmelCase_      :							Tuple       =      tf.placeholder('''float'''			,						[dim]				)
          UpperCAmelCase_      :							Optional[Any]       =      tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(_lowercase			,						_lowercase				)			,						2				)				)				)

          ##This node will figure out which cluster to assign a vector to,
          ##based on Euclidean distances of the vector from the centroids.
          # Placeholder for input
          UpperCAmelCase_      :							int       =      tf.placeholder('''float'''			,						[noofclusters]				)
          UpperCAmelCase_      :							Any       =      tf.argmin(_lowercase			,						0				)

          ##INITIALIZING STATE VARIABLES

          ##This will help initialization of all Variables defined with respect
          ##to the graph. The Variable-initializer should be defined after
          ##all the Variables have been constructed, so that each of them
          ##will be included in the initialization.
          UpperCAmelCase_      :							List[Any]       =      tf.initialize_all_variables()

          # Initialize all variables
          sess.run(_lowercase				)

          ##CLUSTERING ITERATIONS

          # Now perform the Expectation-Maximization steps of K-Means clustering
          # iterations. To keep things simple, we will only do a set number of
          # iterations, instead of using a Stopping Criterion.
          UpperCAmelCase_      :							Tuple       =      100
          for _ in range(_lowercase				):
               ##EXPECTATION STEP
               ##Based on the centroid locations till last iteration, compute
               ##the _expected_ centroid assignments.
               # Iterate over each vector
               for vector_n in range(len(_lowercase				)				):
                    UpperCAmelCase_      :							Optional[int]       =      vectors[vector_n]
                    # Compute Euclidean distance between this vector and each
                    # centroid. Remember that this list cannot be named
                    #'centroid_distances', since that is the input to the
                    # cluster assignment node.
                    UpperCAmelCase_      :							Tuple       =      [
                        sess.run(_lowercase			,						feed_dict={va: vect, va: sess.run(_lowercase				)}				)
                        for centroid in centroids
                    ]
                    # Now use the cluster assignment node, with the distances
                    # as the input
                    UpperCAmelCase_      :							Dict       =      sess.run(
                        _lowercase			,						feed_dict={centroid_distances: distances}				)
                    # Now assign the value to the appropriate state variable
                    sess.run(
                        cluster_assigns[vector_n]			,						feed_dict={assignment_value: assignment}				)

               ##MAXIMIZATION STEP
               # Based on the expected state computed from the Expectation Step,
               # compute the locations of the centroids so as to maximize the
               # overall objective of minimizing within-cluster Sum-of-Squares
               for cluster_n in range(_lowercase				):
                    # Collect all the vectors assigned to this cluster
                    UpperCAmelCase_      :							List[str]       =      [
                        vectors[i]
                        for i in range(len(_lowercase				)				)
                        if sess.run(assignments[i]				) == cluster_n
                    ]
                    # Compute new centroid location
                    UpperCAmelCase_      :							Any       =      sess.run(
                        _lowercase			,						feed_dict={mean_input: array(_lowercase				)}				)
                    # Assign value to appropriate variable
                    sess.run(
                        cent_assigns[cluster_n]			,						feed_dict={centroid_value: new_location}				)

        # Return centroids and assignments
          UpperCAmelCase_      :							Optional[int]       =      sess.run(_lowercase				)
          UpperCAmelCase_      :							int       =      sess.run(_lowercase				)
          return centroids, assignments