


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.
lowerCamelCase						=		{'LayoutLMv2Config', 'LayoutLMv3Config'}





@is_pipeline_test
class 					_a							(				unittest.TestCase):
	_a  :  int          =							MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
	_a  :  List[str]          =							TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

	if model_mapping is not None:
		_a  :  Any          =							{config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
	if tf_model_mapping is not None:
		_a  :  Optional[int]          =							{
		    config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
		}




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

			lowerCAmelCase__   :			Union[str, Any]         =					text_classifier('''This is great !'''		)
			self.assertEqual(nested_simplify(a__		)		,					[{'''label''': '''LABEL_0''', '''score''': 0.504}]		)

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

			lowerCAmelCase__   :			Any         =					text_classifier(['''This is great !''', '''This is bad''']		,					top_k=2		)
			self.assertEqual(
			    nested_simplify(a__		)		,					[
			        [{'''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__   :			Optional[int]         =					text_classifier('''This is great !'''		,					top_k=1		)
			self.assertEqual(nested_simplify(a__		)		,					[{'''label''': '''LABEL_0''', '''score''': 0.504}]		)

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

			lowerCAmelCase__   :			int         =					text_classifier('''This is great !'''		,					return_all_scores=a__		)
			self.assertEqual(
			    nested_simplify(a__		)		,					[[{'''label''': '''LABEL_0''', '''score''': 0.504}, {'''label''': '''LABEL_1''', '''score''': 0.496}]]		)

			lowerCAmelCase__   :			str         =					text_classifier(['''This is great !''', '''Something else''']		,					return_all_scores=a__		)
			self.assertEqual(
			    nested_simplify(a__		)		,					[
			        [{'''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__   :			str         =					text_classifier(['''This is great !''', '''Something else''']		,					return_all_scores=a__		)
			self.assertEqual(
			    nested_simplify(a__		)		,					[
			        {'''label''': '''LABEL_0''', '''score''': 0.504},
			        {'''label''': '''LABEL_0''', '''score''': 0.504},
			    ]		,					)




	@require_torch
	def 							UpperCAmelCase__(					self						:		Union[str, Any]		)->       Optional[Any]:
			import torch

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

			lowerCAmelCase__   :			Union[str, Any]         =					text_classifier('''This is great !'''		)
			self.assertEqual(nested_simplify(a__		)		,					[{'''label''': '''LABEL_0''', '''score''': 0.504}]		)




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

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




	@slow
	@require_torch
	def 							UpperCAmelCase__(					self						:		Tuple		)->       int:
			lowerCAmelCase__   :			Union[str, Any]         =					pipeline('''text-classification'''		)

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




	@slow
	@require_tf
	def 							UpperCAmelCase__(					self						:		Optional[Any]		)->       Any:
			lowerCAmelCase__   :			Tuple         =					pipeline('''text-classification'''		,					framework='''tf'''		)

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




	def 							UpperCAmelCase__(					self						:		int		,					_SCREAMING_SNAKE_CASE						:		Any		,					_SCREAMING_SNAKE_CASE						:		Any		,					_SCREAMING_SNAKE_CASE						:		Any		)->       Optional[int]:
			lowerCAmelCase__   :			List[str]         =					TextClassificationPipeline(model=a__		,					tokenizer=a__		)
			return text_classifier, ["HuggingFace is in", "This is another test"]




	def 							UpperCAmelCase__(					self						:		Any		,					_SCREAMING_SNAKE_CASE						:		Any		,					_SCREAMING_SNAKE_CASE						:		Dict		)->       Dict:
			lowerCAmelCase__   :			Dict         =					text_classifier.model
			# Small inputs because BartTokenizer tiny has maximum position embeddings = 22
			lowerCAmelCase__   :			Any         =					"""HuggingFace is in"""
			lowerCAmelCase__   :			int         =					text_classifier(a__		)

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

			lowerCAmelCase__   :			Optional[Any]         =					["""HuggingFace is in """, """Paris is in France"""]
			lowerCAmelCase__   :			Optional[Any]         =					text_classifier(a__		)
			self.assertEqual(
			    nested_simplify(a__		)		,					[{'''label''': ANY(a__		), '''score''': ANY(a__		)}, {'''label''': ANY(a__		), '''score''': ANY(a__		)}]		,					)
			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(a__		,					top_k=a__		)
			lowerCAmelCase__   :			Optional[Any]         =					len(model.config.idalabel.values()		)
			self.assertEqual(
			    nested_simplify(a__		)		,					[[{'''label''': ANY(a__		), '''score''': ANY(a__		)}] * N, [{'''label''': ANY(a__		), '''score''': ANY(a__		)}] * N]		,					)

			lowerCAmelCase__   :			str         =					{"""text""": """HuggingFace is in """, """text_pair""": """Paris is in France"""}
			lowerCAmelCase__   :			Dict         =					text_classifier(a__		)
			self.assertEqual(
			    nested_simplify(a__		)		,					{'''label''': ANY(a__		), '''score''': ANY(a__		)}		,					)
			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__   :			Any         =					[["""HuggingFace is in """, """Paris is in France"""]]
			with self.assertRaises(a__		):
					text_classifier(a__		)

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





"""simple docstring"""




import numpy as np
import qiskit





def 							SCREAMING_SNAKE_CASE     (			_lowerCamelCase						:       int = 8			,_lowerCamelCase						:       int | None = None	)       ->      str:
  _lowerCAmelCase						:       int  			=     np.random.default_rng(seed=_lowerCamelCase	)

  # Roughly 25% of the qubits will contribute to the key.
  # So we take more than we need.
  _lowerCAmelCase						:       Tuple  			=     6 * key_len
  # Measurement basis for Alice's qubits.
  _lowerCAmelCase						:       Dict  			=     rng.integers(2			,size=_lowerCamelCase	)
  # The set of states Alice will prepare.
  _lowerCAmelCase						:       Tuple  			=     rng.integers(2			,size=_lowerCamelCase	)
  # Measurement basis for Bob's qubits.
  _lowerCAmelCase						:       Union[str, Any]  			=     rng.integers(2			,size=_lowerCamelCase	)

  # Quantum Circuit to simulate BB84
  _lowerCAmelCase						:       Dict  			=     qiskit.QuantumCircuit(_lowerCamelCase			,name="""BB84"""	)

  # Alice prepares her qubits according to rules above.
  for index, _ in enumerate(_lowerCamelCase	):
    if alice_state[index] == 1:
      bbaa_circ.x(_lowerCamelCase	)
    if alice_basis[index] == 1:
      bbaa_circ.h(_lowerCamelCase	)
  bbaa_circ.barrier()

  # Bob measures the received qubits according to rules above.
  for index, _ in enumerate(_lowerCamelCase	):
    if bob_basis[index] == 1:
      bbaa_circ.h(_lowerCamelCase	)

  bbaa_circ.barrier()
  bbaa_circ.measure_all()

  # Simulate the quantum circuit.
  _lowerCAmelCase						:       int  			=     qiskit.Aer.get_backend("""aer_simulator"""	)
  # We only need to run one shot because the key is unique.
  # Multiple shots will produce the same key.
  _lowerCAmelCase						:       List[str]  			=     qiskit.execute(_lowerCamelCase			,_lowerCamelCase			,shots=1			,seed_simulator=_lowerCamelCase	)
  # Returns the result of measurement.
  _lowerCAmelCase						:       List[Any]  			=     job.result().get_counts(_lowerCamelCase	).most_frequent()

  # Extracting the generated key from the simulation results.
  # Only keep measurement results where Alice and Bob chose the same basis.
  _lowerCAmelCase						:       str  			=     """""".join(
      [
          result_bit
          for alice_basis_bit, bob_basis_bit, result_bit in zip(
              _lowerCamelCase			,_lowerCamelCase			,_lowerCamelCase	)
          if alice_basis_bit == bob_basis_bit
      ]	)

  # Get final key. Pad with 0 if too short, otherwise truncate.
  _lowerCAmelCase						:       List[Any]  			=     gen_key[:key_len] if len(_lowerCamelCase	) >= key_len else gen_key.ljust(_lowerCamelCase			,"""0"""	)
  return key


if __name__ == "__main__":
     print(F"""The generated key is : {bbaa(8, seed=0)}""")
     from doctest import testmod

     testmod()




