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







@is_pipeline_test
class UpperCAmelCase__	( unittest.TestCase	):





  """simple docstring"""

  __UpperCAmelCase				:				str   =					MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
  __UpperCAmelCase				:				int   =					TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

  if model_mapping is not None:
    __UpperCAmelCase				:				List[str]   =					{config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
  if tf_model_mapping is not None:
    __UpperCAmelCase				:				List[str]   =					{
        config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
    }


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


     '''simple docstring'''






     _a				:	Any			=   pipeline(
         task='text-classification'							,model='hf-internal-testing/tiny-random-distilbert'							,framework='pt'       )

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

     _a				:	Union[str, 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}]       )

     _a				:	Dict			=   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}],
         ]							,)

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

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

     _a				:	Optional[Any]			=   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}]]       )

     _a				:	Union[str, Any]			=   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}],
         ]							,)

     _a				:	Optional[int]			=   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   __lowercase		(		self      :     str       ):


     '''simple docstring'''






     import torch

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

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


  @require_tf
  def   __lowercase		(		self      :     List[Any]       ):


     '''simple docstring'''






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

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


  @slow
  @require_torch
  def   __lowercase		(		self      :     str       ):


     '''simple docstring'''






     _a				:	Tuple			=   pipeline('text-classification'       )

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


  @slow
  @require_tf
  def   __lowercase		(		self      :     Tuple       ):


     '''simple docstring'''






     _a				:	Tuple			=   pipeline('text-classification'							,framework='tf'       )

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


  def   __lowercase		(		self      :     str							,_a      :     int							,_a      :     Optional[Any]							,_a      :     int       ):


     '''simple docstring'''






     _a				:	List[str]			=   TextClassificationPipeline(model=_a							,tokenizer=_a       )
     return text_classifier, ["HuggingFace is in", "This is another test"]


  def   __lowercase		(		self      :     Tuple							,_a      :     Dict							,_a      :     Optional[Any]       ):


     '''simple docstring'''






     _a				:	Any			=   text_classifier.model
     # Small inputs because BartTokenizer tiny has maximum position embeddings = 22
     _a				:	str			=   'HuggingFace is in'
     _a				:	Union[str, Any]			=   text_classifier(_a       )

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

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

     _a				:	Union[str, Any]			=   {'text': 'HuggingFace is in ', 'text_pair': 'Paris is in France'}
     _a				:	Union[str, Any]			=   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.
     _a				:	Dict			=   [['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
     _a				:	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 unittest

import numpy as np
import torch

from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device


enable_full_determinism()







class UpperCAmelCase__	( unittest.TestCase	):





  """simple docstring"""

  @property
  def   __lowercase		(		self      :     List[str]       ):


     '''simple docstring'''






     torch.manual_seed(0       )
     _a				:	int			=   UNetaDModel(
         block_out_channels=(32, 64)							,layers_per_block=2							,sample_size=32							,in_channels=3							,out_channels=3							,down_block_types=('DownBlock2D', 'AttnDownBlock2D')							,up_block_types=('AttnUpBlock2D', 'UpBlock2D')							,)
     return model


  def   __lowercase		(		self      :     Optional[Any]       ):


     '''simple docstring'''






     _a				:	str			=   self.dummy_uncond_unet
     _a				:	int			=   PNDMScheduler()

     _a				:	str			=   PNDMPipeline(unet=_a							,scheduler=_a       )
     pndm.to(_a       )
     pndm.set_progress_bar_config(disable=_a       )

     _a				:	Optional[int]			=   torch.manual_seed(0       )
     _a				:	Optional[Any]			=   pndm(generator=_a							,num_inference_steps=20							,output_type='numpy'       ).images

     _a				:	List[str]			=   torch.manual_seed(0       )
     _a				:	Any			=   pndm(generator=_a							,num_inference_steps=20							,output_type='numpy'							,return_dict=_a       )[0]

     _a				:	List[Any]			=   image[0, -3:, -3:, -1]
     _a				:	Any			=   image_from_tuple[0, -3:, -3:, -1]

     assert image.shape == (1, 32, 32, 3)
     _a				:	List[Any]			=   np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0]       )

     assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1E-2
     assert np.abs(image_from_tuple_slice.flatten() - expected_slice       ).max() < 1E-2







@slow
@require_torch
class UpperCAmelCase__	( unittest.TestCase	):





  """simple docstring"""

  def   __lowercase		(		self      :     Tuple       ):


     '''simple docstring'''






     _a				:	List[str]			=   'google/ddpm-cifar10-32'

     _a				:	str			=   UNetaDModel.from_pretrained(_a       )
     _a				:	Union[str, Any]			=   PNDMScheduler()

     _a				:	Tuple			=   PNDMPipeline(unet=_a							,scheduler=_a       )
     pndm.to(_a       )
     pndm.set_progress_bar_config(disable=_a       )
     _a				:	str			=   torch.manual_seed(0       )
     _a				:	Optional[Any]			=   pndm(generator=_a							,output_type='numpy'       ).images

     _a				:	Dict			=   image[0, -3:, -3:, -1]

     assert image.shape == (1, 32, 32, 3)
     _a				:	Tuple			=   np.array([0.1564, 0.1_4645, 0.1406, 0.1_4715, 0.1_2425, 0.1_4045, 0.1_3115, 0.1_2175, 0.125]       )

     assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1E-2



