



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






@is_pipeline_test
class 		_UpperCamelCase						(							unittest.TestCase					):


			'''simple docstring'''

			_A   :	Union[str, Any]    					=	MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
			_A   :	Union[str, Any]    					=	TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

			if model_mapping is not None:
						_A   :	Union[str, 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   :	int    					=	{
						    config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
						}

			@require_torch
			def UpperCamelCase__      (							self  :				Optional[int]		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	str					 =	pipeline(
					    task="""text-classification"""							,  model="""hf-internal-testing/tiny-random-distilbert"""							,  framework="""pt"""		)

					__SCREAMING_SNAKE_CASE :	str					 =	text_classifier("""This is great !"""		)
					self.assertEqual(nested_simplify(lowerCAmelCase__		)							,  [{"""label""": """LABEL_0""", """score""": 0.5_04}]		)

					__SCREAMING_SNAKE_CASE :	Union[str, Any]					 =	text_classifier("""This is great !"""							,  top_k=2		)
					self.assertEqual(
					    nested_simplify(lowerCAmelCase__		)							,  [{"""label""": """LABEL_0""", """score""": 0.5_04}, {"""label""": """LABEL_1""", """score""": 0.4_96}]		)

					__SCREAMING_SNAKE_CASE :	str					 =	text_classifier(["""This is great !""", """This is bad"""]							,  top_k=2		)
					self.assertEqual(
					    nested_simplify(lowerCAmelCase__		)							,  [
					        [{"""label""": """LABEL_0""", """score""": 0.5_04}, {"""label""": """LABEL_1""", """score""": 0.4_96}],
					        [{"""label""": """LABEL_0""", """score""": 0.5_04}, {"""label""": """LABEL_1""", """score""": 0.4_96}],
					    ]							,  )

					__SCREAMING_SNAKE_CASE :	List[str]					 =	text_classifier("""This is great !"""							,  top_k=1		)
					self.assertEqual(nested_simplify(lowerCAmelCase__		)							,  [{"""label""": """LABEL_0""", """score""": 0.5_04}]		)

					# Legacy behavior
					__SCREAMING_SNAKE_CASE :	Optional[int]					 =	text_classifier("""This is great !"""							,  return_all_scores=lowerCAmelCase__		)
					self.assertEqual(nested_simplify(lowerCAmelCase__		)							,  [{"""label""": """LABEL_0""", """score""": 0.5_04}]		)

					__SCREAMING_SNAKE_CASE :	Tuple					 =	text_classifier("""This is great !"""							,  return_all_scores=lowerCAmelCase__		)
					self.assertEqual(
					    nested_simplify(lowerCAmelCase__		)							,  [[{"""label""": """LABEL_0""", """score""": 0.5_04}, {"""label""": """LABEL_1""", """score""": 0.4_96}]]		)

					__SCREAMING_SNAKE_CASE :	Optional[int]					 =	text_classifier(["""This is great !""", """Something else"""]							,  return_all_scores=lowerCAmelCase__		)
					self.assertEqual(
					    nested_simplify(lowerCAmelCase__		)							,  [
					        [{"""label""": """LABEL_0""", """score""": 0.5_04}, {"""label""": """LABEL_1""", """score""": 0.4_96}],
					        [{"""label""": """LABEL_0""", """score""": 0.5_04}, {"""label""": """LABEL_1""", """score""": 0.4_96}],
					    ]							,  )

					__SCREAMING_SNAKE_CASE :	Dict					 =	text_classifier(["""This is great !""", """Something else"""]							,  return_all_scores=lowerCAmelCase__		)
					self.assertEqual(
					    nested_simplify(lowerCAmelCase__		)							,  [
					        {"""label""": """LABEL_0""", """score""": 0.5_04},
					        {"""label""": """LABEL_0""", """score""": 0.5_04},
					    ]							,  )

			@require_torch
			def UpperCamelCase__      (							self  :				str		):





					"""simple docstring"""






					import torch

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

					__SCREAMING_SNAKE_CASE :	List[str]					 =	text_classifier("""This is great !"""		)
					self.assertEqual(nested_simplify(lowerCAmelCase__		)							,  [{"""label""": """LABEL_0""", """score""": 0.5_04}]		)

			@require_tf
			def UpperCamelCase__      (							self  :				Tuple		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	int					 =	pipeline(
					    task="""text-classification"""							,  model="""hf-internal-testing/tiny-random-distilbert"""							,  framework="""tf"""		)

					__SCREAMING_SNAKE_CASE :	List[Any]					 =	text_classifier("""This is great !"""		)
					self.assertEqual(nested_simplify(lowerCAmelCase__		)							,  [{"""label""": """LABEL_0""", """score""": 0.5_04}]		)

			@slow
			@require_torch
			def UpperCamelCase__      (							self  :				Union[str, Any]		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	Tuple					 =	pipeline("""text-classification"""		)

					__SCREAMING_SNAKE_CASE :	List[str]					 =	text_classifier("""This is great !"""		)
					self.assertEqual(nested_simplify(lowerCAmelCase__		)							,  [{"""label""": """POSITIVE""", """score""": 1.0}]		)
					__SCREAMING_SNAKE_CASE :	int					 =	text_classifier("""This is bad !"""		)
					self.assertEqual(nested_simplify(lowerCAmelCase__		)							,  [{"""label""": """NEGATIVE""", """score""": 1.0}]		)
					__SCREAMING_SNAKE_CASE :	int					 =	text_classifier("""Birds are a type of animal"""		)
					self.assertEqual(nested_simplify(lowerCAmelCase__		)							,  [{"""label""": """POSITIVE""", """score""": 0.9_88}]		)

			@slow
			@require_tf
			def UpperCamelCase__      (							self  :				List[Any]		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	Any					 =	pipeline("""text-classification"""							,  framework="""tf"""		)

					__SCREAMING_SNAKE_CASE :	Dict					 =	text_classifier("""This is great !"""		)
					self.assertEqual(nested_simplify(lowerCAmelCase__		)							,  [{"""label""": """POSITIVE""", """score""": 1.0}]		)
					__SCREAMING_SNAKE_CASE :	Optional[int]					 =	text_classifier("""This is bad !"""		)
					self.assertEqual(nested_simplify(lowerCAmelCase__		)							,  [{"""label""": """NEGATIVE""", """score""": 1.0}]		)
					__SCREAMING_SNAKE_CASE :	Union[str, Any]					 =	text_classifier("""Birds are a type of animal"""		)
					self.assertEqual(nested_simplify(lowerCAmelCase__		)							,  [{"""label""": """POSITIVE""", """score""": 0.9_88}]		)

			def UpperCamelCase__      (							self  :				Union[str, Any]							,  lowerCAmelCase__  :				List[str]							,  lowerCAmelCase__  :				Union[str, Any]							,  lowerCAmelCase__  :				Dict		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	Tuple					 =	TextClassificationPipeline(model=lowerCAmelCase__							,  tokenizer=lowerCAmelCase__		)
					return text_classifier, ["HuggingFace is in", "This is another test"]



			def UpperCamelCase__      (							self  :				List[Any]							,  lowerCAmelCase__  :				Optional[int]							,  lowerCAmelCase__  :				Optional[int]		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	Any					 =	text_classifier.model
					# Small inputs because BartTokenizer tiny has maximum position embeddings = 22
					__SCREAMING_SNAKE_CASE :	Dict					 =	"""HuggingFace is in"""
					__SCREAMING_SNAKE_CASE :	int					 =	text_classifier(lowerCAmelCase__		)

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

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

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

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




'''simple docstring'''




import gc
import unittest

from diffusers import FlaxControlNetModel, FlaxStableDiffusionControlNetPipeline
from diffusers.utils import is_flax_available, load_image, slow
from diffusers.utils.testing_utils import require_flax


if is_flax_available():
						import jax
						import jax.numpy as jnp
						from flax.jax_utils import replicate
						from flax.training.common_utils import shard






@slow
@require_flax
class 		_UpperCamelCase						(							unittest.TestCase					):


			'''simple docstring'''

			def UpperCamelCase__      (							self  :				Optional[Any]		):





					"""simple docstring"""






					super().tearDown()
					gc.collect()

			def UpperCamelCase__      (							self  :				List[Any]		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE ,		__SCREAMING_SNAKE_CASE :	int					 =	FlaxControlNetModel.from_pretrained(
					    """lllyasviel/sd-controlnet-canny"""							,  from_pt=lowerCAmelCase__							,  dtype=jnp.bfloataa		)
					__SCREAMING_SNAKE_CASE ,		__SCREAMING_SNAKE_CASE :	Tuple					 =	FlaxStableDiffusionControlNetPipeline.from_pretrained(
					    """runwayml/stable-diffusion-v1-5"""							,  controlnet=lowerCAmelCase__							,  from_pt=lowerCAmelCase__							,  dtype=jnp.bfloataa		)
					__SCREAMING_SNAKE_CASE :	str					 =	controlnet_params

					__SCREAMING_SNAKE_CASE :	str					 =	"""bird"""
					__SCREAMING_SNAKE_CASE :	Optional[int]					 =	jax.device_count()
					__SCREAMING_SNAKE_CASE :	str					 =	pipe.prepare_text_inputs([prompts] * num_samples		)

					__SCREAMING_SNAKE_CASE :	Tuple					 =	load_image(
					    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png"""		)
					__SCREAMING_SNAKE_CASE :	List[Any]					 =	pipe.prepare_image_inputs([canny_image] * num_samples		)

					__SCREAMING_SNAKE_CASE :	Union[str, Any]					 =	jax.random.PRNGKey(0		)
					__SCREAMING_SNAKE_CASE :	Union[str, Any]					 =	jax.random.split(lowerCAmelCase__							,  jax.device_count()		)

					__SCREAMING_SNAKE_CASE :	Optional[int]					 =	replicate(lowerCAmelCase__		)
					__SCREAMING_SNAKE_CASE :	Union[str, Any]					 =	shard(lowerCAmelCase__		)
					__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	shard(lowerCAmelCase__		)

					__SCREAMING_SNAKE_CASE :	List[Any]					 =	pipe(
					    prompt_ids=lowerCAmelCase__							,  image=lowerCAmelCase__							,  params=lowerCAmelCase__							,  prng_seed=lowerCAmelCase__							,  num_inference_steps=5_0							,  jit=lowerCAmelCase__							,  ).images
					assert images.shape == (jax.device_count(), 1, 7_6_8, 5_1_2, 3)

					__SCREAMING_SNAKE_CASE :	Union[str, Any]					 =	images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:]		)
					__SCREAMING_SNAKE_CASE :	Tuple					 =	images[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1]

					__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	jnp.asarray(jax.device_get(image_slice.flatten()		)		)
					__SCREAMING_SNAKE_CASE :	Tuple					 =	jnp.array(
					    [0.16_79_69, 0.11_66_99, 0.08_15_43, 0.15_42_97, 0.13_28_12, 0.10_88_87, 0.16_99_22, 0.16_99_22, 0.20_50_78]		)
					print(F"output_slice: {output_slice}"		)
					assert jnp.abs(output_slice - expected_slice		).max() < 1E-2



			def UpperCamelCase__      (							self  :				str		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE ,		__SCREAMING_SNAKE_CASE :	Union[str, Any]					 =	FlaxControlNetModel.from_pretrained(
					    """lllyasviel/sd-controlnet-openpose"""							,  from_pt=lowerCAmelCase__							,  dtype=jnp.bfloataa		)
					__SCREAMING_SNAKE_CASE ,		__SCREAMING_SNAKE_CASE :	Any					 =	FlaxStableDiffusionControlNetPipeline.from_pretrained(
					    """runwayml/stable-diffusion-v1-5"""							,  controlnet=lowerCAmelCase__							,  from_pt=lowerCAmelCase__							,  dtype=jnp.bfloataa		)
					__SCREAMING_SNAKE_CASE :	Union[str, Any]					 =	controlnet_params

					__SCREAMING_SNAKE_CASE :	List[str]					 =	"""Chef in the kitchen"""
					__SCREAMING_SNAKE_CASE :	int					 =	jax.device_count()
					__SCREAMING_SNAKE_CASE :	Tuple					 =	pipe.prepare_text_inputs([prompts] * num_samples		)

					__SCREAMING_SNAKE_CASE :	Any					 =	load_image(
					    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/pose.png"""		)
					__SCREAMING_SNAKE_CASE :	Dict					 =	pipe.prepare_image_inputs([pose_image] * num_samples		)

					__SCREAMING_SNAKE_CASE :	Dict					 =	jax.random.PRNGKey(0		)
					__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	jax.random.split(lowerCAmelCase__							,  jax.device_count()		)

					__SCREAMING_SNAKE_CASE :	List[Any]					 =	replicate(lowerCAmelCase__		)
					__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	shard(lowerCAmelCase__		)
					__SCREAMING_SNAKE_CASE :	List[Any]					 =	shard(lowerCAmelCase__		)

					__SCREAMING_SNAKE_CASE :	Tuple					 =	pipe(
					    prompt_ids=lowerCAmelCase__							,  image=lowerCAmelCase__							,  params=lowerCAmelCase__							,  prng_seed=lowerCAmelCase__							,  num_inference_steps=5_0							,  jit=lowerCAmelCase__							,  ).images
					assert images.shape == (jax.device_count(), 1, 7_6_8, 5_1_2, 3)

					__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:]		)
					__SCREAMING_SNAKE_CASE :	List[Any]					 =	images[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1]

					__SCREAMING_SNAKE_CASE :	Tuple					 =	jnp.asarray(jax.device_get(image_slice.flatten()		)		)
					__SCREAMING_SNAKE_CASE :	Tuple					 =	jnp.array(
					    [[0.27_14_84, 0.26_17_19, 0.27_53_91, 0.27_73_44, 0.27_92_97, 0.29_10_16, 0.29_49_22, 0.30_27_34, 0.30_27_34]]		)
					print(F"output_slice: {output_slice}"		)
					assert jnp.abs(output_slice - expected_slice		).max() < 1E-2