



"""simple docstring"""






from typing import List, Union

import numpy as np

from ..tokenization_utils import TruncationStrategy
from ..utils import add_end_docstrings, logging
from .base import PIPELINE_INIT_ARGS, ArgumentHandler, ChunkPipeline


lowerCAmelCase__      =    logging.get_logger(__name__)






class 	__snake_case	(     _lowercase):




  def 						SCREAMING_SNAKE_CASE    (			self					:						str						, __lowerCAmelCase					:						int		):






         """simple docstring"""






         if isinstance(__lowerCAmelCase						, __lowerCAmelCase		):
                _lowerCamelCase						:    Any         =			[label.strip() for label in labels.split(''','''		) if label.strip()]
         return labels




  def __call__(			self					:						str						, __lowerCAmelCase					:						Union[str, Any]						, __lowerCAmelCase					:						List[Any]						, __lowerCAmelCase					:						List[Any]		):






         """simple docstring"""






         if len(__lowerCAmelCase		) == 0 or len(__lowerCAmelCase		) == 0:
                raise ValueError('''You must include at least one label and at least one sequence.'''		)
         if hypothesis_template.format(labels[0]		) == hypothesis_template:
                raise ValueError(
                    (
                        '''The provided hypothesis_template "{}" was not able to be formatted with the target labels. '''
                        '''Make sure the passed template includes formatting syntax such as {{}} where the label should go.'''
                    ).format(__lowerCAmelCase		)		)

         if isinstance(__lowerCAmelCase						, __lowerCAmelCase		):
                _lowerCamelCase						:    int         =			[sequences]

         _lowerCamelCase						:    Union[str, Any]         =			[]
         for sequence in sequences:
                sequence_pairs.extend([[sequence, hypothesis_template.format(__lowerCAmelCase		)] for label in labels]		)

         return sequence_pairs, sequences






@add_end_docstrings(_lowercase)
class 	__snake_case	(     _lowercase):




  def __init__(			self					:						Union[str, Any]						, __lowerCAmelCase					:						str=ZeroShotClassificationArgumentHandler()						, *__lowerCAmelCase					:						Dict						, **__lowerCAmelCase					:						Optional[Any]		):






         """simple docstring"""






         _lowerCamelCase						:    str         =			args_parser
         super().__init__(*__lowerCAmelCase						, **__lowerCAmelCase		)
         if self.entailment_id == -1:
                logger.warning(
                    '''Failed to determine \'entailment\' label id from the label2id mapping in the model config. Setting to '''
                    '''-1. Define a descriptive label2id mapping in the model config to ensure correct outputs.'''		)




  @property
  def 						SCREAMING_SNAKE_CASE    (			self					:						Dict		):






         """simple docstring"""






         for label, ind in self.model.config.labelaid.items():
                if label.lower().startswith('''entail'''		):
                       return ind
         return -1




  def 						SCREAMING_SNAKE_CASE    (			self					:						Any						, __lowerCAmelCase					:						int						, __lowerCAmelCase					:						Union[str, Any]=True						, __lowerCAmelCase					:						Any=True						, __lowerCAmelCase					:						List[Any]=TruncationStrategy.ONLY_FIRST						, **__lowerCAmelCase					:						List[str]		):






         """simple docstring"""






         _lowerCamelCase						:    Tuple         =			self.framework
         if self.tokenizer.pad_token is None:
                # Override for tokenizers not supporting padding
                logger.error(
                    '''Tokenizer was not supporting padding necessary for zero-shot, attempting to use '''
                    ''' `pad_token=eos_token`'''		)
                _lowerCamelCase						:    Optional[Any]         =			self.tokenizer.eos_token
         try:
                _lowerCamelCase						:    Any         =			self.tokenizer(
                    __lowerCAmelCase						, add_special_tokens=__lowerCAmelCase						, return_tensors=__lowerCAmelCase						, padding=__lowerCAmelCase						, truncation=__lowerCAmelCase						, )
         except Exception as e:
                if "too short" in str(__lowerCAmelCase		):
                       # tokenizers might yell that we want to truncate
                       # to a value that is not even reached by the input.
                       # In that case we don't want to truncate.
                       # It seems there's not a really better way to catch that
                       # exception.

                       _lowerCamelCase						:    Dict         =			self.tokenizer(
                           __lowerCAmelCase						, add_special_tokens=__lowerCAmelCase						, return_tensors=__lowerCAmelCase						, padding=__lowerCAmelCase						, truncation=TruncationStrategy.DO_NOT_TRUNCATE						, )
                else:
                       raise e

         return inputs




  def 						SCREAMING_SNAKE_CASE    (			self					:						str						, **__lowerCAmelCase					:						Union[str, Any]		):






         """simple docstring"""






         if kwargs.get('''multi_class'''						, __lowerCAmelCase		) is not None:
                _lowerCamelCase						:    List[Any]         =			kwargs['''multi_class''']
                logger.warning(
                    '''The `multi_class` argument has been deprecated and renamed to `multi_label`. '''
                    '''`multi_class` will be removed in a future version of Transformers.'''		)
         _lowerCamelCase						:    List[Any]         =			{}
         if "candidate_labels" in kwargs:
                _lowerCamelCase						:    Any         =			self._args_parser._parse_labels(kwargs['''candidate_labels''']		)
         if "hypothesis_template" in kwargs:
                _lowerCamelCase						:    Optional[Any]         =			kwargs['''hypothesis_template''']

         _lowerCamelCase						:    Optional[Any]         =			{}
         if "multi_label" in kwargs:
                _lowerCamelCase						:    Union[str, Any]         =			kwargs['''multi_label''']
         return preprocess_params, {}, postprocess_params




  def __call__(			self					:						Any						, __lowerCAmelCase					:						Union[str, List[str]]						, *__lowerCAmelCase					:						Tuple						, **__lowerCAmelCase					:						Tuple						, ):






         """simple docstring"""






         if len(__lowerCAmelCase		) == 0:
                pass
         elif len(__lowerCAmelCase		) == 1 and "candidate_labels" not in kwargs:
                _lowerCamelCase						:    Tuple         =			args[0]
         else:
                raise ValueError(f'''Unable to understand extra arguments {args}'''		)

         return super().__call__(__lowerCAmelCase						, **__lowerCAmelCase		)




  def 						SCREAMING_SNAKE_CASE    (			self					:						Dict						, __lowerCAmelCase					:						Optional[Any]						, __lowerCAmelCase					:						Union[str, Any]=None						, __lowerCAmelCase					:						int="This example is {}."		):






         """simple docstring"""






         _lowerCamelCase      ,   _lowerCamelCase						:    Any         =			self._args_parser(__lowerCAmelCase						, __lowerCAmelCase						, __lowerCAmelCase		)

         for i, (candidate_label, sequence_pair) in enumerate(zip(__lowerCAmelCase						, __lowerCAmelCase		)		):
                _lowerCamelCase						:    Tuple         =			self._parse_and_tokenize([sequence_pair]		)

                yield {
                    "candidate_label": candidate_label,
                    "sequence": sequences[0],
                    "is_last": i == len(__lowerCAmelCase		) - 1,
                    **model_input,
                }




  def 						SCREAMING_SNAKE_CASE    (			self					:						Any						, __lowerCAmelCase					:						List[Any]		):






         """simple docstring"""






         _lowerCamelCase						:    List[str]         =			inputs['''candidate_label''']
         _lowerCamelCase						:    List[str]         =			inputs['''sequence''']
         _lowerCamelCase						:    Any         =			{k: inputs[k] for k in self.tokenizer.model_input_names}
         _lowerCamelCase						:    str         =			self.model(**__lowerCAmelCase		)

         _lowerCamelCase						:    Tuple         =			{
             '''candidate_label''': candidate_label,
             '''sequence''': sequence,
             '''is_last''': inputs['''is_last'''],
             **outputs,
         }
         return model_outputs




  def 						SCREAMING_SNAKE_CASE    (			self					:						List[str]						, __lowerCAmelCase					:						Tuple						, __lowerCAmelCase					:						List[Any]=False		):






         """simple docstring"""






         _lowerCamelCase						:    List[str]         =			[outputs['''candidate_label'''] for outputs in model_outputs]
         _lowerCamelCase						:    Optional[int]         =			[outputs['''sequence'''] for outputs in model_outputs]
         _lowerCamelCase						:    Any         =			np.concatenate([output['''logits'''].numpy() for output in model_outputs]		)
         _lowerCamelCase						:    Optional[int]         =			logits.shape[0]
         _lowerCamelCase						:    Union[str, Any]         =			len(__lowerCAmelCase		)
         _lowerCamelCase						:    List[str]         =			N // n
         _lowerCamelCase						:    int         =			logits.reshape((num_sequences, n, -1)		)

         if multi_label or len(__lowerCAmelCase		) == 1:
                # softmax over the entailment vs. contradiction dim for each label independently
                _lowerCamelCase						:    Optional[int]         =			self.entailment_id
                _lowerCamelCase						:    Optional[Any]         =			-1 if entailment_id == 0 else 0
                _lowerCamelCase						:    List[Any]         =			reshaped_outputs[..., [contradiction_id, entailment_id]]
                _lowerCamelCase						:    str         =			np.exp(__lowerCAmelCase		) / np.exp(__lowerCAmelCase		).sum(-1						, keepdims=__lowerCAmelCase		)
                _lowerCamelCase						:    Tuple         =			scores[..., 1]
         else:
                # softmax the "entailment" logits over all candidate labels
                _lowerCamelCase						:    Any         =			reshaped_outputs[..., self.entailment_id]
                _lowerCamelCase						:    Tuple         =			np.exp(__lowerCAmelCase		) / np.exp(__lowerCAmelCase		).sum(-1						, keepdims=__lowerCAmelCase		)

         _lowerCamelCase						:    List[Any]         =			list(reversed(scores[0].argsort()		)		)
         return {
             "sequence": sequences[0],
             "labels": [candidate_labels[i] for i in top_inds],
             "scores": scores[0, top_inds].tolist(),
         }







"""simple docstring"""






import random
import unittest

import numpy as np
import torch

from diffusers import (
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionUpscalePipeline,
    PNDMScheduler,
)
from diffusers.utils import floats_tensor
from diffusers.utils.testing_utils import (
    is_onnx_available,
    load_image,
    nightly,
    require_onnxruntime,
    require_torch_gpu,
)

from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin


if is_onnx_available():
   import onnxruntime as ort






class 	__snake_case	(     _lowercase  ,					unittest.TestCase):
  # TODO: is there an appropriate internal test set?
  snake_case__    :       List[str]        =						"ssube/stable-diffusion-x4-upscaler-onnx"




  def 						SCREAMING_SNAKE_CASE    (			self					:						Optional[Any]						, __lowerCAmelCase					:						int=0		):






         """simple docstring"""






         _lowerCamelCase						:    Tuple         =			floats_tensor((1, 3, 1_2_8, 1_2_8)						, rng=random.Random(__lowerCAmelCase		)		)
         _lowerCamelCase						:    Union[str, Any]         =			torch.manual_seed(__lowerCAmelCase		)
         _lowerCamelCase						:    Tuple         =			{
             '''prompt''': '''A painting of a squirrel eating a burger''',
             '''image''': image,
             '''generator''': generator,
             '''num_inference_steps''': 3,
             '''guidance_scale''': 7.5,
             '''output_type''': '''numpy''',
         }
         return inputs




  def 						SCREAMING_SNAKE_CASE    (			self					:						Optional[Any]		):






         """simple docstring"""






         _lowerCamelCase						:    Union[str, Any]         =			OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint						, provider='''CPUExecutionProvider'''		)
         pipe.set_progress_bar_config(disable=__lowerCAmelCase		)

         _lowerCamelCase						:    Union[str, Any]         =			self.get_dummy_inputs()
         _lowerCamelCase						:    Any         =			pipe(**__lowerCAmelCase		).images
         _lowerCamelCase						:    Dict         =			image[0, -3:, -3:, -1].flatten()

         # started as 128, should now be 512
         assert image.shape == (1, 5_1_2, 5_1_2, 3)
         _lowerCamelCase						:    str         =			np.array(
             [0.6_97_47_82, 0.68_90_20_93, 0.70_13_58_85, 0.7_58_36_18, 0.7_80_45_45, 0.7_85_49_12, 0.78_66_74_26, 0.78_74_38_63, 0.78_07_02_23]		)
         assert np.abs(image_slice - expected_slice		).max() < 1E-1




  def 						SCREAMING_SNAKE_CASE    (			self					:						List[Any]		):






         """simple docstring"""






         _lowerCamelCase						:    Optional[Any]         =			OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint						, provider='''CPUExecutionProvider'''		)
         _lowerCamelCase						:    List[str]         =			PNDMScheduler.from_config(pipe.scheduler.config						, skip_prk_steps=__lowerCAmelCase		)
         pipe.set_progress_bar_config(disable=__lowerCAmelCase		)

         _lowerCamelCase						:    int         =			self.get_dummy_inputs()
         _lowerCamelCase						:    Optional[Any]         =			pipe(**__lowerCAmelCase		).images
         _lowerCamelCase						:    str         =			image[0, -3:, -3:, -1]

         assert image.shape == (1, 5_1_2, 5_1_2, 3)
         _lowerCamelCase						:    Optional[int]         =			np.array(
             [0.6_89_88_92, 0.59_24_05_56, 0.52_49_95_27, 0.58_86_62_15, 0.52_25_82_35, 0.52_57_27_15, 0.62_41_44_73, 0.6_17_43_87, 0.6_21_49_64]		)
         assert np.abs(image_slice.flatten() - expected_slice		).max() < 1E-1




  def 						SCREAMING_SNAKE_CASE    (			self					:						Optional[int]		):






         """simple docstring"""






         _lowerCamelCase						:    Optional[int]         =			OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint						, provider='''CPUExecutionProvider'''		)
         _lowerCamelCase						:    Optional[int]         =			DPMSolverMultistepScheduler.from_config(pipe.scheduler.config		)
         pipe.set_progress_bar_config(disable=__lowerCAmelCase		)

         _lowerCamelCase						:    Tuple         =			self.get_dummy_inputs()
         _lowerCamelCase						:    str         =			pipe(**__lowerCAmelCase		).images
         _lowerCamelCase						:    Tuple         =			image[0, -3:, -3:, -1]

         assert image.shape == (1, 5_1_2, 5_1_2, 3)
         _lowerCamelCase						:    str         =			np.array(
             [0.7_65_92_78, 0.76_43_76_64, 0.75_57_91_07, 0.7_69_11_16, 0.77_66_69_86, 0.7_72_76_72, 0.7_75_86_64, 0.7_81_22_26, 0.76_94_25_15]		)

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




  def 						SCREAMING_SNAKE_CASE    (			self					:						Any		):






         """simple docstring"""






         _lowerCamelCase						:    Any         =			OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint						, provider='''CPUExecutionProvider'''		)
         _lowerCamelCase						:    Union[str, Any]         =			EulerDiscreteScheduler.from_config(pipe.scheduler.config		)
         pipe.set_progress_bar_config(disable=__lowerCAmelCase		)

         _lowerCamelCase						:    Optional[Any]         =			self.get_dummy_inputs()
         _lowerCamelCase						:    Tuple         =			pipe(**__lowerCAmelCase		).images
         _lowerCamelCase						:    Union[str, Any]         =			image[0, -3:, -3:, -1]

         assert image.shape == (1, 5_1_2, 5_1_2, 3)
         _lowerCamelCase						:    Union[str, Any]         =			np.array(
             [0.6_97_47_82, 0.68_90_20_93, 0.70_13_58_85, 0.7_58_36_18, 0.7_80_45_45, 0.7_85_49_12, 0.78_66_74_26, 0.78_74_38_63, 0.78_07_02_23]		)
         assert np.abs(image_slice.flatten() - expected_slice		).max() < 1E-1




  def 						SCREAMING_SNAKE_CASE    (			self					:						Any		):






         """simple docstring"""






         _lowerCamelCase						:    Dict         =			OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint						, provider='''CPUExecutionProvider'''		)
         _lowerCamelCase						:    int         =			EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config		)
         pipe.set_progress_bar_config(disable=__lowerCAmelCase		)

         _lowerCamelCase						:    Union[str, Any]         =			self.get_dummy_inputs()
         _lowerCamelCase						:    List[Any]         =			pipe(**__lowerCAmelCase		).images
         _lowerCamelCase						:    Optional[Any]         =			image[0, -3:, -3:, -1]

         assert image.shape == (1, 5_1_2, 5_1_2, 3)
         _lowerCamelCase						:    Optional[int]         =			np.array(
             [0.77_42_44_96, 0.77_36_01, 0.7_64_52_88, 0.7_76_95_98, 0.7_77_27_39, 0.7_73_86_88, 0.78_18_72_33, 0.77_87_95_84, 0.76_70_43]		)

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






@nightly
@require_onnxruntime
@require_torch_gpu
class 	__snake_case	(     unittest.TestCase):




  @property
  def 						SCREAMING_SNAKE_CASE    (			self					:						str		):






         """simple docstring"""






         return (
             "CUDAExecutionProvider",
             {
                 "gpu_mem_limit": "15000000000",  # 15GB
                 "arena_extend_strategy": "kSameAsRequested",
             },
         )




  @property
  def 						SCREAMING_SNAKE_CASE    (			self					:						Any		):






         """simple docstring"""






         _lowerCamelCase						:    Optional[int]         =			ort.SessionOptions()
         _lowerCamelCase						:    List[str]         =			False
         return options




  def 						SCREAMING_SNAKE_CASE    (			self					:						Optional[int]		):






         """simple docstring"""






         _lowerCamelCase						:    Optional[int]         =			load_image(
             '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
             '''/img2img/sketch-mountains-input.jpg'''		)
         _lowerCamelCase						:    Any         =			init_image.resize((1_2_8, 1_2_8)		)
         # using the PNDM scheduler by default
         _lowerCamelCase						:    List[str]         =			OnnxStableDiffusionUpscalePipeline.from_pretrained(
             '''ssube/stable-diffusion-x4-upscaler-onnx'''						, provider=self.gpu_provider						, sess_options=self.gpu_options						, )
         pipe.set_progress_bar_config(disable=__lowerCAmelCase		)

         _lowerCamelCase						:    int         =			'''A fantasy landscape, trending on artstation'''

         _lowerCamelCase						:    List[Any]         =			torch.manual_seed(0		)
         _lowerCamelCase						:    List[str]         =			pipe(
             prompt=__lowerCAmelCase						, image=__lowerCAmelCase						, guidance_scale=7.5						, num_inference_steps=1_0						, generator=__lowerCAmelCase						, output_type='''np'''						, )
         _lowerCamelCase						:    List[Any]         =			output.images
         _lowerCamelCase						:    List[Any]         =			images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1]

         assert images.shape == (1, 5_1_2, 5_1_2, 3)
         _lowerCamelCase						:    str         =			np.array([0.48_83, 0.49_47, 0.49_80, 0.49_75, 0.49_82, 0.49_80, 0.50_00, 0.50_06, 0.49_72]		)
         # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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




  def 						SCREAMING_SNAKE_CASE    (			self					:						str		):






         """simple docstring"""






         _lowerCamelCase						:    Union[str, Any]         =			load_image(
             '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
             '''/img2img/sketch-mountains-input.jpg'''		)
         _lowerCamelCase						:    int         =			init_image.resize((1_2_8, 1_2_8)		)
         _lowerCamelCase						:    str         =			LMSDiscreteScheduler.from_pretrained(
             '''ssube/stable-diffusion-x4-upscaler-onnx'''						, subfolder='''scheduler'''		)
         _lowerCamelCase						:    Dict         =			OnnxStableDiffusionUpscalePipeline.from_pretrained(
             '''ssube/stable-diffusion-x4-upscaler-onnx'''						, scheduler=__lowerCAmelCase						, provider=self.gpu_provider						, sess_options=self.gpu_options						, )
         pipe.set_progress_bar_config(disable=__lowerCAmelCase		)

         _lowerCamelCase						:    Optional[int]         =			'''A fantasy landscape, trending on artstation'''

         _lowerCamelCase						:    int         =			torch.manual_seed(0		)
         _lowerCamelCase						:    List[str]         =			pipe(
             prompt=__lowerCAmelCase						, image=__lowerCAmelCase						, guidance_scale=7.5						, num_inference_steps=2_0						, generator=__lowerCAmelCase						, output_type='''np'''						, )
         _lowerCamelCase						:    Union[str, Any]         =			output.images
         _lowerCamelCase						:    Optional[Any]         =			images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1]

         assert images.shape == (1, 5_1_2, 5_1_2, 3)
         _lowerCamelCase						:    str         =			np.array(
             [0.50_17_37_53, 0.50_22_33_56, 0.50_20_39, 0.50_23_30_36, 0.5_02_37_25, 0.5_02_26_01, 0.5_01_87_58, 0.50_23_40_85, 0.50_24_15_66]		)
         # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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


