





from collections import UserDict
from typing import Union

import numpy as np
import requests

from ..utils import (
    add_end_docstrings,
    logging,
)
from .audio_classification import ffmpeg_read
from .base import PIPELINE_INIT_ARGS, Pipeline


__A				:    Union[str, Any]       =   logging.get_logger(__name__)

@add_end_docstrings(a_			)
class 	A_       (a_			):
	def __init__(    self							,					**_A		):






				'''simple docstring'''







				super().__init__(**_A		)

				if self.framework != "pt":
							raise ValueError(F"""The {self.__class__} is only available in PyTorch."""		)
				# No specific FOR_XXX available yet
	def __call__(    self							,					_A							,					**_A		):






				'''simple docstring'''







				return super().__call__(_A							,					**_A		)
	def      _lowercase				(    self							,					**_A		):






				'''simple docstring'''







				UpperCAmelCase   		=				{}
				if "candidate_labels" in kwargs:
							UpperCAmelCase   		=				kwargs['''candidate_labels''']
				if "hypothesis_template" in kwargs:
							UpperCAmelCase   		=				kwargs['''hypothesis_template''']

				return preprocess_params, {}, {}
	def      _lowercase				(    self							,					_A							,					_A=None							,					_A="This is a sound of {}."		):






				'''simple docstring'''







				if isinstance(_A							,					_A		):
							if audio.startswith('''http://'''		) or audio.startswith('''https://'''		):
										# We need to actually check for a real protocol, otherwise it's impossible to use a local file
										# like http_huggingface_co.png
										UpperCAmelCase   		=				requests.get(_A		).content
							else:
										with open(_A							,					'''rb'''		) as f:
													UpperCAmelCase   		=				f.read()

				if isinstance(_A							,					_A		):
							UpperCAmelCase   		=				ffmpeg_read(_A							,					self.feature_extractor.sampling_rate		)

				if not isinstance(_A							,					np.ndarray		):
							raise ValueError('''We expect a numpy ndarray as input'''		)
				if len(audio.shape		) != 1:
							raise ValueError('''We expect a single channel audio input for ZeroShotAudioClassificationPipeline'''		)

				UpperCAmelCase   		=				self.feature_extractor(
				    [audio]							,					sampling_rate=self.feature_extractor.sampling_rate							,					return_tensors='''pt'''		)
				UpperCAmelCase   		=				candidate_labels
				UpperCAmelCase   		=				[hypothesis_template.format(_A		) for x in candidate_labels]
				UpperCAmelCase   		=				self.tokenizer(_A							,					return_tensors=self.framework							,					padding=_A		)
				UpperCAmelCase   		=				[text_inputs]
				return inputs
	def      _lowercase				(    self							,					_A		):






				'''simple docstring'''







				UpperCAmelCase   		=				model_inputs.pop('''candidate_labels'''		)
				UpperCAmelCase   		=				model_inputs.pop('''text_inputs'''		)
				if isinstance(text_inputs[0]							,					_A		):
							UpperCAmelCase   		=				text_inputs[0]
				else:
							# Batching case.
							UpperCAmelCase   		=				text_inputs[0][0]

				UpperCAmelCase   		=				self.model(**_A							,					**_A		)

				UpperCAmelCase   		=				{
				    '''candidate_labels''': candidate_labels,
				    '''logits''': outputs.logits_per_audio,
				}
				return model_outputs







	def      _lowercase				(    self							,					_A		):






				'''simple docstring'''







				UpperCAmelCase   		=				model_outputs.pop('''candidate_labels'''		)
				UpperCAmelCase   		=				model_outputs['''logits'''][0]

				if self.framework == "pt":
							UpperCAmelCase   		=				logits.softmax(dim=0		)
							UpperCAmelCase   		=				probs.tolist()
				else:
							raise ValueError('''`tf` framework not supported.'''		)

				UpperCAmelCase   		=				[
				    {'''score''': score, '''label''': candidate_label}
				    for score, candidate_label in sorted(zip(_A							,					_A		)							,					key=lambda _A		: -x[0]		)
				]
				return result










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 	A_       (a_			):
	UpperCAmelCase__					=			42
	UpperCAmelCase__					=			42
	def __init__(    self							,					_A							,					_A		):






				'''simple docstring'''







				super().__init__()
				self.register_modules(unet=_A							,					scheduler=_A		)







	@torch.no_grad()
	def __call__(    self							,					_A = 1							,					_A = 5_0							,					_A = None							,					_A = "pil"							,					_A = True							,					**_A							,					):






				'''simple docstring'''







				UpperCAmelCase   		=				self.unet.config.sample_size
				UpperCAmelCase   		=				(batch_size, 3, img_size, img_size)

				UpperCAmelCase   		=				self.unet

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

				self.scheduler.set_timesteps(_A		)

				for t in self.progress_bar(self.scheduler.timesteps		):
							# here sigma_t == t_i from the paper
							UpperCAmelCase   		=				self.scheduler.schedule[t]
							UpperCAmelCase   		=				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
							UpperCAmelCase		,			UpperCAmelCase   		=				self.scheduler.add_noise_to_input(_A							,					_A							,					generator=_A		)

							# 3. Predict the noise residual given the noise magnitude `sigma_hat`
							# The model inputs and output are adjusted by following eq. (213) in [1].
							UpperCAmelCase   		=				(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
							UpperCAmelCase   		=				self.scheduler.step(_A							,					_A							,					_A							,					_A		)

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

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

				if not return_dict:
							return (image,)

				return ImagePipelineOutput(images=_A		)



