




"""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


a							      =     logging.get_logger(__name__)





class 							lowercase_			(	__lowerCAmelCase				):



 '''simple docstring'''

 def      lowerCAmelCase_				(					self			:			int       ,				_UpperCAmelCase			:			str						):
       if isinstance(_UpperCAmelCase       ,				_UpperCAmelCase						):
             _A     =  [label.strip() for label in labels.split(','						) if label.strip()]
       return labels



 def __call__(					self			:			Optional[Any]       ,				_UpperCAmelCase			:			str       ,				_UpperCAmelCase			:			Tuple       ,				_UpperCAmelCase			:			Tuple						):
       if len(_UpperCAmelCase						) == 0 or len(_UpperCAmelCase						) == 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(_UpperCAmelCase						)						)

       if isinstance(_UpperCAmelCase       ,				_UpperCAmelCase						):
             _A     =  [sequences]

       _A     =  []
       for sequence in sequences:
             sequence_pairs.extend([[sequence, hypothesis_template.format(_UpperCAmelCase						)] for label in labels]						)

       return sequence_pairs, sequences





@add_end_docstrings(__lowerCAmelCase				)
class 							lowercase_			(	__lowerCAmelCase				):



 '''simple docstring'''

 def __init__(					self			:			Any       ,				_UpperCAmelCase			:			int=ZeroShotClassificationArgumentHandler()       ,				*_UpperCAmelCase			:			Dict       ,				**_UpperCAmelCase			:			Optional[int]						):
       _A     =  args_parser
       super().__init__(*_UpperCAmelCase       ,				**_UpperCAmelCase						)
       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      lowerCAmelCase_				(					self			:			int						):
       for label, ind in self.model.config.labelaid.items():
             if label.lower().startswith('entail'						):
                   return ind
       return -1

 def      lowerCAmelCase_				(					self			:			Union[str, Any]       ,				_UpperCAmelCase			:			List[Any]       ,				_UpperCAmelCase			:			str=True       ,				_UpperCAmelCase			:			List[str]=True       ,				_UpperCAmelCase			:			List[str]=TruncationStrategy.ONLY_FIRST       ,				**_UpperCAmelCase			:			Dict						):
       _A     =  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`'						)
             _A     =  self.tokenizer.eos_token
       try:
             _A     =  self.tokenizer(
                 _UpperCAmelCase       ,				add_special_tokens=_UpperCAmelCase       ,				return_tensors=_UpperCAmelCase       ,				padding=_UpperCAmelCase       ,				truncation=_UpperCAmelCase       ,				)
       except Exception as e:
             if "too short" in str(_UpperCAmelCase						):
                   # 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.

                   _A     =  self.tokenizer(
                       _UpperCAmelCase       ,				add_special_tokens=_UpperCAmelCase       ,				return_tensors=_UpperCAmelCase       ,				padding=_UpperCAmelCase       ,				truncation=TruncationStrategy.DO_NOT_TRUNCATE       ,				)
             else:
                   raise e

       return inputs

 def      lowerCAmelCase_				(					self			:			int       ,				**_UpperCAmelCase			:			Tuple						):
       if kwargs.get('multi_class'       ,				_UpperCAmelCase						) is not None:
             _A     =  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.'						)
       _A     =  {}
       if "candidate_labels" in kwargs:
             _A     =  self._args_parser._parse_labels(kwargs['candidate_labels']						)
       if "hypothesis_template" in kwargs:
             _A     =  kwargs['hypothesis_template']

       _A     =  {}
       if "multi_label" in kwargs:
             _A     =  kwargs['multi_label']
       return preprocess_params, {}, postprocess_params

 def __call__(					self			:			Any       ,				_UpperCAmelCase			:			Union[str, List[str]]       ,				*_UpperCAmelCase			:			int       ,				**_UpperCAmelCase			:			Dict       ,				):
       if len(_UpperCAmelCase						) == 0:
             pass
       elif len(_UpperCAmelCase						) == 1 and "candidate_labels" not in kwargs:
             _A     =  args[0]
       else:
             raise ValueError(F'''Unable to understand extra arguments {args}'''						)

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

 def      lowerCAmelCase_				(					self			:			List[Any]       ,				_UpperCAmelCase			:			List[str]       ,				_UpperCAmelCase			:			Optional[int]=None       ,				_UpperCAmelCase			:			List[Any]="This example is {}."						):
       _A  ,       _A     =  self._args_parser(_UpperCAmelCase       ,				_UpperCAmelCase       ,				_UpperCAmelCase						)

       for i, (candidate_label, sequence_pair) in enumerate(zip(_UpperCAmelCase       ,				_UpperCAmelCase						)						):
             _A     =  self._parse_and_tokenize([sequence_pair]						)

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

 def      lowerCAmelCase_				(					self			:			Optional[int]       ,				_UpperCAmelCase			:			int						):
       _A     =  inputs['candidate_label']
       _A     =  inputs['sequence']
       _A     =  {k: inputs[k] for k in self.tokenizer.model_input_names}
       _A     =  self.model(**_UpperCAmelCase						)

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



 def      lowerCAmelCase_				(					self			:			Union[str, Any]       ,				_UpperCAmelCase			:			Optional[Any]       ,				_UpperCAmelCase			:			Dict=False						):
       _A     =  [outputs['candidate_label'] for outputs in model_outputs]
       _A     =  [outputs['sequence'] for outputs in model_outputs]
       _A     =  np.concatenate([output['logits'].numpy() for output in model_outputs]						)
       _A     =  logits.shape[0]
       _A     =  len(_UpperCAmelCase						)
       _A     =  N // n
       _A     =  logits.reshape((num_sequences, n, -1)						)

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

       _A     =  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"""

from typing import List, Optional, Tuple, Union

import torch

from ...models import UNetaDModel
from ...schedulers import KarrasVeScheduler
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput





class 							lowercase_			(	__lowerCAmelCase				):



 '''simple docstring'''
 UpperCAmelCase       :	UNetaDModel
 UpperCAmelCase       :	KarrasVeScheduler

 def __init__(					self			:			Any       ,				_UpperCAmelCase			:			UNetaDModel       ,				_UpperCAmelCase			:			KarrasVeScheduler						):
       super().__init__()
       self.register_modules(unet=_UpperCAmelCase       ,				scheduler=_UpperCAmelCase						)



 @torch.no_grad()
 def __call__(					self			:			Optional[int]       ,				_UpperCAmelCase			:			int = 1       ,				_UpperCAmelCase			:			int = 50       ,				_UpperCAmelCase			:			Optional[Union[torch.Generator, List[torch.Generator]]] = None       ,				_UpperCAmelCase			:			Optional[str] = "pil"       ,				_UpperCAmelCase			:			bool = True       ,				**_UpperCAmelCase			:			Optional[Any]       ,				):
       _A     =  self.unet.config.sample_size
       _A     =  (batch_size, 3, img_size, img_size)

       _A     =  self.unet

       # sample x_0 ~ N(0, sigma_0^2 * I)
       _A     =  randn_tensor(_UpperCAmelCase       ,				generator=_UpperCAmelCase       ,				device=self.device						) * self.scheduler.init_noise_sigma

       self.scheduler.set_timesteps(_UpperCAmelCase						)

       for t in self.progress_bar(self.scheduler.timesteps						):
             # here sigma_t == t_i from the paper
             _A     =  self.scheduler.schedule[t]
             _A     =  self.scheduler.schedule[t - 1] if t > 0 else 0

             # 1. Select temporarily increased noise level sigma_hat
             # 2. Add new noise to move from sample_i to sample_hat
             _A  ,       _A     =  self.scheduler.add_noise_to_input(_UpperCAmelCase       ,				_UpperCAmelCase       ,				generator=_UpperCAmelCase						)

             # 3. Predict the noise residual given the noise magnitude `sigma_hat`
             # The model inputs and output are adjusted by following eq. (213) in [1].
             _A     =  (sigma_hat / 2) * model((sample_hat + 1) / 2       ,				sigma_hat / 2						).sample

             # 4. Evaluate dx/dt at sigma_hat
             # 5. Take Euler step from sigma to sigma_prev
             _A     =  self.scheduler.step(_UpperCAmelCase       ,				_UpperCAmelCase       ,				_UpperCAmelCase       ,				_UpperCAmelCase						)

             if sigma_prev != 0:
                   # 6. Apply 2nd order correction
                   # The model inputs and output are adjusted by following eq. (213) in [1].
                   _A     =  (sigma_prev / 2) * model((step_output.prev_sample + 1) / 2       ,				sigma_prev / 2						).sample
                   _A     =  self.scheduler.step_correct(
                       _UpperCAmelCase       ,				_UpperCAmelCase       ,				_UpperCAmelCase       ,				_UpperCAmelCase       ,				step_output.prev_sample       ,				step_output['derivative']       ,				)
             _A     =  step_output.prev_sample

       _A     =  (sample / 2 + 0.5).clamp(0       ,				1						)
       _A     =  sample.cpu().permute(0       ,				2       ,				3       ,				1						).numpy()
       if output_type == "pil":
             _A     =  self.numpy_to_pil(_UpperCAmelCase						)

       if not return_dict:
             return (image,)

       return ImagePipelineOutput(images=_UpperCAmelCase						)

