
"""simple docstring"""

import unittest

from transformers import (
    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TextClassificationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow

from .test_pipelines_common import ANY


# These 2 model types require different inputs than those of the usual text models.
_A						=			{'LayoutLMv2Config', 'LayoutLMv3Config'}






@is_pipeline_test
class 	_lowercase       (    unittest.TestCase		):
 lowercase_				=     MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
 lowercase_				=     TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

 if model_mapping is not None:
  lowercase_				=     {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
 if tf_model_mapping is not None:
  lowercase_				=     {
      config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
  }




 @require_torch
 def       _UpperCamelCase   (			self )		->							Optional[Any]:
   lowerCamelCase					:      List[Any]          =   pipeline(
       task='text-classification'		,			model='hf-internal-testing/tiny-random-distilbert'		,			framework='pt' )

   lowerCamelCase					:      Tuple          =   text_classifier('This is great !' )
   self.assertEqual(nested_simplify(UpperCAmelCase_ )		,			[{'label': 'LABEL_0', 'score': 0.504}] )

   lowerCamelCase					:      List[Any]          =   text_classifier('This is great !'		,			top_k=2 )
   self.assertEqual(
       nested_simplify(UpperCAmelCase_ )		,			[{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}] )

   lowerCamelCase					:      List[str]          =   text_classifier(['This is great !', 'This is bad']		,			top_k=2 )
   self.assertEqual(
       nested_simplify(UpperCAmelCase_ )		,			[
           [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}],
           [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}],
       ]		,			)

   lowerCamelCase					:      Tuple          =   text_classifier('This is great !'		,			top_k=1 )
   self.assertEqual(nested_simplify(UpperCAmelCase_ )		,			[{'label': 'LABEL_0', 'score': 0.504}] )

   # Legacy behavior
   lowerCamelCase					:      int          =   text_classifier('This is great !'		,			return_all_scores=UpperCAmelCase_ )
   self.assertEqual(nested_simplify(UpperCAmelCase_ )		,			[{'label': 'LABEL_0', 'score': 0.504}] )

   lowerCamelCase					:      Optional[Any]          =   text_classifier('This is great !'		,			return_all_scores=UpperCAmelCase_ )
   self.assertEqual(
       nested_simplify(UpperCAmelCase_ )		,			[[{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}]] )

   lowerCamelCase					:      List[Any]          =   text_classifier(['This is great !', 'Something else']		,			return_all_scores=UpperCAmelCase_ )
   self.assertEqual(
       nested_simplify(UpperCAmelCase_ )		,			[
           [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}],
           [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}],
       ]		,			)

   lowerCamelCase					:      Any          =   text_classifier(['This is great !', 'Something else']		,			return_all_scores=UpperCAmelCase_ )
   self.assertEqual(
       nested_simplify(UpperCAmelCase_ )		,			[
           {'label': 'LABEL_0', 'score': 0.504},
           {'label': 'LABEL_0', 'score': 0.504},
       ]		,			)




 @require_torch
 def       _UpperCamelCase   (			self )		->							Tuple:
   import torch

   lowerCamelCase					:      Any          =   pipeline(
       task='text-classification'		,			model='hf-internal-testing/tiny-random-distilbert'		,			framework='pt'		,			device=torch.device('cpu' )		,			)

   lowerCamelCase					:      Optional[int]          =   text_classifier('This is great !' )
   self.assertEqual(nested_simplify(UpperCAmelCase_ )		,			[{'label': 'LABEL_0', 'score': 0.504}] )




 @require_tf
 def       _UpperCamelCase   (			self )		->							Optional[Any]:
   lowerCamelCase					:      int          =   pipeline(
       task='text-classification'		,			model='hf-internal-testing/tiny-random-distilbert'		,			framework='tf' )

   lowerCamelCase					:      int          =   text_classifier('This is great !' )
   self.assertEqual(nested_simplify(UpperCAmelCase_ )		,			[{'label': 'LABEL_0', 'score': 0.504}] )




 @slow
 @require_torch
 def       _UpperCamelCase   (			self )		->							Union[str, Any]:
   lowerCamelCase					:      Optional[int]          =   pipeline('text-classification' )

   lowerCamelCase					:      str          =   text_classifier('This is great !' )
   self.assertEqual(nested_simplify(UpperCAmelCase_ )		,			[{'label': 'POSITIVE', 'score': 1.0}] )
   lowerCamelCase					:      Any          =   text_classifier('This is bad !' )
   self.assertEqual(nested_simplify(UpperCAmelCase_ )		,			[{'label': 'NEGATIVE', 'score': 1.0}] )
   lowerCamelCase					:      Tuple          =   text_classifier('Birds are a type of animal' )
   self.assertEqual(nested_simplify(UpperCAmelCase_ )		,			[{'label': 'POSITIVE', 'score': 0.988}] )




 @slow
 @require_tf
 def       _UpperCamelCase   (			self )		->							int:
   lowerCamelCase					:      Dict          =   pipeline('text-classification'		,			framework='tf' )

   lowerCamelCase					:      Dict          =   text_classifier('This is great !' )
   self.assertEqual(nested_simplify(UpperCAmelCase_ )		,			[{'label': 'POSITIVE', 'score': 1.0}] )
   lowerCamelCase					:      int          =   text_classifier('This is bad !' )
   self.assertEqual(nested_simplify(UpperCAmelCase_ )		,			[{'label': 'NEGATIVE', 'score': 1.0}] )
   lowerCamelCase					:      Union[str, Any]          =   text_classifier('Birds are a type of animal' )
   self.assertEqual(nested_simplify(UpperCAmelCase_ )		,			[{'label': 'POSITIVE', 'score': 0.988}] )




 def       _UpperCamelCase   (			self		,			UpperCAmelCase_		,			UpperCAmelCase_		,			UpperCAmelCase_ )		->							List[Any]:
   lowerCamelCase					:      Tuple          =   TextClassificationPipeline(model=UpperCAmelCase_		,			tokenizer=UpperCAmelCase_ )
   return text_classifier, ["HuggingFace is in", "This is another test"]




 def       _UpperCamelCase   (			self		,			UpperCAmelCase_		,			UpperCAmelCase_ )		->							Any:
   lowerCamelCase					:      Tuple          =   text_classifier.model
   # Small inputs because BartTokenizer tiny has maximum position embeddings = 22
   lowerCamelCase					:      Union[str, Any]          =   '''HuggingFace is in'''
   lowerCamelCase					:      Dict          =   text_classifier(UpperCAmelCase_ )

   self.assertEqual(nested_simplify(UpperCAmelCase_ )		,			[{'label': ANY(UpperCAmelCase_ ), 'score': ANY(UpperCAmelCase_ )}] )
   self.assertTrue(outputs[0]['label'] in model.config.idalabel.values() )

   lowerCamelCase					:      Tuple          =   ['''HuggingFace is in ''', '''Paris is in France''']
   lowerCamelCase					:      Any          =   text_classifier(UpperCAmelCase_ )
   self.assertEqual(
       nested_simplify(UpperCAmelCase_ )		,			[{'label': ANY(UpperCAmelCase_ ), 'score': ANY(UpperCAmelCase_ )}, {'label': ANY(UpperCAmelCase_ ), 'score': ANY(UpperCAmelCase_ )}]		,			)
   self.assertTrue(outputs[0]['label'] in model.config.idalabel.values() )
   self.assertTrue(outputs[1]['label'] in model.config.idalabel.values() )

   # Forcing to get all results with `top_k=None`
   # This is NOT the legacy format
   lowerCamelCase					:      Dict          =   text_classifier(UpperCAmelCase_		,			top_k=UpperCAmelCase_ )
   lowerCamelCase					:      Optional[int]          =   len(model.config.idalabel.values() )
   self.assertEqual(
       nested_simplify(UpperCAmelCase_ )		,			[[{'label': ANY(UpperCAmelCase_ ), 'score': ANY(UpperCAmelCase_ )}] * N, [{'label': ANY(UpperCAmelCase_ ), 'score': ANY(UpperCAmelCase_ )}] * N]		,			)

   lowerCamelCase					:      List[str]          =   {'''text''': '''HuggingFace is in ''', '''text_pair''': '''Paris is in France'''}
   lowerCamelCase					:      Any          =   text_classifier(UpperCAmelCase_ )
   self.assertEqual(
       nested_simplify(UpperCAmelCase_ )		,			{'label': ANY(UpperCAmelCase_ ), 'score': ANY(UpperCAmelCase_ )}		,			)
   self.assertTrue(outputs['label'] in model.config.idalabel.values() )

   # This might be used a text pair, but tokenizer + pipe interaction
   # makes it hard to understand that it's not using the pair properly
   # https://github.com/huggingface/transformers/issues/17305
   # We disabled this usage instead as it was outputting wrong outputs.
   lowerCamelCase					:      List[Any]          =   [['''HuggingFace is in ''', '''Paris is in France''']]
   with self.assertRaises(UpperCAmelCase_ ):
     text_classifier(UpperCAmelCase_ )

   # This used to be valid for doing text pairs
   # We're keeping it working because of backward compatibility
   lowerCamelCase					:      Any          =   text_classifier([[['HuggingFace is in ', 'Paris is in France']]] )
   self.assertEqual(
       nested_simplify(UpperCAmelCase_ )		,			[{'label': ANY(UpperCAmelCase_ ), 'score': ANY(UpperCAmelCase_ )}]		,			)
   self.assertTrue(outputs[0]['label'] in model.config.idalabel.values() )








"""simple docstring"""

import numpy as np
def 		UpperCAmelCase (		a_,						a_,						a_ = 1E-12,						a_ = 100,						):





		'''simple docstring'''


		assert np.shape(a_      )[0] == np.shape(a_      )[1]
		# Ensure proper dimensionality.
		assert np.shape(a_      )[0] == np.shape(a_      )[0]
		# Ensure inputs are either both complex or both real
		assert np.iscomplexobj(a_      ) == np.iscomplexobj(a_      )
		lowerCamelCase					:      Optional[int]          =   np.iscomplexobj(a_      )
		if is_complex:
				# Ensure complex input_matrix is Hermitian
				assert np.array_equal(a_,						input_matrix.conj().T      )

		# Set convergence to False. Will define convergence when we exceed max_iterations
		# or when we have small changes from one iteration to next.

		lowerCamelCase					:      Union[str, Any]          =   False
		lowerCamelCase					:      List[str]          =   0
		lowerCamelCase					:      Any          =   0
		lowerCamelCase					:      Dict          =   1E12

		while not convergence:
				# Multiple matrix by the vector.
				lowerCamelCase					:      Optional[int]          =   np.dot(a_,						a_      )
				# Normalize the resulting output vector.
				lowerCamelCase					:      Optional[int]          =   w / np.linalg.norm(a_      )
				# Find rayleigh quotient
				# (faster than usual b/c we know vector is normalized already)
				lowerCamelCase					:      Optional[Any]          =   vector.conj().T if is_complex else vector.T
				lowerCamelCase					:      str          =   np.dot(a_,						np.dot(a_,						a_      )      )

				# Check convergence.
				lowerCamelCase					:      Optional[int]          =   np.abs(lambda_ - lambda_previous      ) / lambda_
				iterations += 1

				if error <= error_tol or iterations >= max_iterations:
						lowerCamelCase					:      int          =   True

				lowerCamelCase					:      Optional[Any]          =   lambda_

		if is_complex:
				lowerCamelCase					:      Any          =   np.real(lambda_      )

		return lambda_, vector
def 		UpperCAmelCase (		):





		'''simple docstring'''


		lowerCamelCase					:      str          =   np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]]      )
		lowerCamelCase					:      str          =   np.array([41, 4, 20]      )
		lowerCamelCase					:      Optional[Any]          =   real_input_matrix.astype(np.complexaaa      )
		lowerCamelCase					:      Dict          =   np.triu(1j * complex_input_matrix,						1      )
		complex_input_matrix += imag_matrix
		complex_input_matrix += -1 * imag_matrix.T
		lowerCamelCase					:      List[Any]          =   np.array([41, 4, 20]      ).astype(np.complexaaa      )

		for problem_type in ["real", "complex"]:
				if problem_type == "real":
						lowerCamelCase					:      str          =   real_input_matrix
						lowerCamelCase					:      Any          =   real_vector
				elif problem_type == "complex":
						lowerCamelCase					:      str          =   complex_input_matrix
						lowerCamelCase					:      Dict          =   complex_vector

				# Our implementation.
				lowerCamelCase     ,   lowerCamelCase					:      List[str]          =   power_iteration(a_,						a_      )

				# Numpy implementation.

				# Get eigenvalues and eigenvectors using built-in numpy
				# eigh (eigh used for symmetric or hermetian matrices).
				lowerCamelCase     ,   lowerCamelCase					:      Optional[Any]          =   np.linalg.eigh(a_      )
				# Last eigenvalue is the maximum one.
				lowerCamelCase					:      Dict          =   eigen_values[-1]
				# Last column in this matrix is eigenvector corresponding to largest eigenvalue.
				lowerCamelCase					:      List[str]          =   eigen_vectors[:, -1]

				# Check our implementation and numpy gives close answers.
				assert np.abs(eigen_value - eigen_value_max      ) <= 1E-6
				# Take absolute values element wise of each eigenvector.
				# as they are only unique to a minus sign.
				assert np.linalg.norm(np.abs(a_      ) - np.abs(a_      )      ) <= 1E-6


if __name__ == "__main__":
					import doctest

					doctest.testmod()
					test_power_iteration()






