






__lowerCamelCase	:		int										=   """0.18.2"""

from .configuration_utils import ConfigMixin
from .utils import (
    OptionalDependencyNotAvailable,
    is_flax_available,
    is_inflect_available,
    is_invisible_watermark_available,
    is_k_diffusion_available,
    is_k_diffusion_version,
    is_librosa_available,
    is_note_seq_available,
    is_onnx_available,
    is_scipy_available,
    is_torch_available,
    is_torchsde_available,
    is_transformers_available,
    is_transformers_version,
    is_unidecode_available,
    logging,
)


try:
       if not is_onnx_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       from .utils.dummy_onnx_objects import *  # noqa F403
else:
       from .pipelines import OnnxRuntimeModel

try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       from .utils.dummy_pt_objects import *  # noqa F403
else:
       from .models import (
           AutoencoderKL,
           ControlNetModel,
           ModelMixin,
           PriorTransformer,
           TaFilmDecoder,
           TransformeraDModel,
           UNetaDModel,
           UNetaDConditionModel,
           UNetaDModel,
           UNetaDConditionModel,
           VQModel,
       )
       from .optimization import (
           get_constant_schedule,
           get_constant_schedule_with_warmup,
           get_cosine_schedule_with_warmup,
           get_cosine_with_hard_restarts_schedule_with_warmup,
           get_linear_schedule_with_warmup,
           get_polynomial_decay_schedule_with_warmup,
           get_scheduler,
       )
       from .pipelines import (
           AudioPipelineOutput,
           ConsistencyModelPipeline,
           DanceDiffusionPipeline,
           DDIMPipeline,
           DDPMPipeline,
           DiffusionPipeline,
           DiTPipeline,
           ImagePipelineOutput,
           KarrasVePipeline,
           LDMPipeline,
           LDMSuperResolutionPipeline,
           PNDMPipeline,
           RePaintPipeline,
           ScoreSdeVePipeline,
       )
       from .schedulers import (
           CMStochasticIterativeScheduler,
           DDIMInverseScheduler,
           DDIMParallelScheduler,
           DDIMScheduler,
           DDPMParallelScheduler,
           DDPMScheduler,
           DEISMultistepScheduler,
           DPMSolverMultistepInverseScheduler,
           DPMSolverMultistepScheduler,
           DPMSolverSinglestepScheduler,
           EulerAncestralDiscreteScheduler,
           EulerDiscreteScheduler,
           HeunDiscreteScheduler,
           IPNDMScheduler,
           KarrasVeScheduler,
           KDPMaAncestralDiscreteScheduler,
           KDPMaDiscreteScheduler,
           PNDMScheduler,
           RePaintScheduler,
           SchedulerMixin,
           ScoreSdeVeScheduler,
           UnCLIPScheduler,
           UniPCMultistepScheduler,
           VQDiffusionScheduler,
       )
       from .training_utils import EMAModel

try:
       if not (is_torch_available() and is_scipy_available()):
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       from .utils.dummy_torch_and_scipy_objects import *  # noqa F403
else:
       from .schedulers import LMSDiscreteScheduler

try:
       if not (is_torch_available() and is_torchsde_available()):
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       from .utils.dummy_torch_and_torchsde_objects import *  # noqa F403
else:
       from .schedulers import DPMSolverSDEScheduler

try:
       if not (is_torch_available() and is_transformers_available()):
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       from .utils.dummy_torch_and_transformers_objects import *  # noqa F403
else:
       from .pipelines import (
           AltDiffusionImgaImgPipeline,
           AltDiffusionPipeline,
           AudioLDMPipeline,
           CycleDiffusionPipeline,
           IFImgaImgPipeline,
           IFImgaImgSuperResolutionPipeline,
           IFInpaintingPipeline,
           IFInpaintingSuperResolutionPipeline,
           IFPipeline,
           IFSuperResolutionPipeline,
           ImageTextPipelineOutput,
           KandinskyImgaImgPipeline,
           KandinskyInpaintPipeline,
           KandinskyPipeline,
           KandinskyPriorPipeline,
           KandinskyVaaControlnetImgaImgPipeline,
           KandinskyVaaControlnetPipeline,
           KandinskyVaaImgaImgPipeline,
           KandinskyVaaInpaintPipeline,
           KandinskyVaaPipeline,
           KandinskyVaaPriorEmbaEmbPipeline,
           KandinskyVaaPriorPipeline,
           LDMTextToImagePipeline,
           PaintByExamplePipeline,
           SemanticStableDiffusionPipeline,
           ShapEImgaImgPipeline,
           ShapEPipeline,
           StableDiffusionAttendAndExcitePipeline,
           StableDiffusionControlNetImgaImgPipeline,
           StableDiffusionControlNetInpaintPipeline,
           StableDiffusionControlNetPipeline,
           StableDiffusionDepthaImgPipeline,
           StableDiffusionDiffEditPipeline,
           StableDiffusionImageVariationPipeline,
           StableDiffusionImgaImgPipeline,
           StableDiffusionInpaintPipeline,
           StableDiffusionInpaintPipelineLegacy,
           StableDiffusionInstructPixaPixPipeline,
           StableDiffusionLatentUpscalePipeline,
           StableDiffusionLDMaDPipeline,
           StableDiffusionModelEditingPipeline,
           StableDiffusionPanoramaPipeline,
           StableDiffusionParadigmsPipeline,
           StableDiffusionPipeline,
           StableDiffusionPipelineSafe,
           StableDiffusionPixaPixZeroPipeline,
           StableDiffusionSAGPipeline,
           StableDiffusionUpscalePipeline,
           StableUnCLIPImgaImgPipeline,
           StableUnCLIPPipeline,
           TextToVideoSDPipeline,
           TextToVideoZeroPipeline,
           UnCLIPImageVariationPipeline,
           UnCLIPPipeline,
           UniDiffuserModel,
           UniDiffuserPipeline,
           UniDiffuserTextDecoder,
           VersatileDiffusionDualGuidedPipeline,
           VersatileDiffusionImageVariationPipeline,
           VersatileDiffusionPipeline,
           VersatileDiffusionTextToImagePipeline,
           VideoToVideoSDPipeline,
           VQDiffusionPipeline,
       )

try:
       if not (is_torch_available() and is_transformers_available() and is_invisible_watermark_available()):
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       from .utils.dummy_torch_and_transformers_and_invisible_watermark_objects import *  # noqa F403
else:
       from .pipelines import StableDiffusionXLImgaImgPipeline, StableDiffusionXLPipeline

try:
       if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()):
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       from .utils.dummy_torch_and_transformers_and_k_diffusion_objects import *  # noqa F403
else:
       from .pipelines import StableDiffusionKDiffusionPipeline

try:
       if not (is_torch_available() and is_transformers_available() and is_onnx_available()):
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       from .utils.dummy_torch_and_transformers_and_onnx_objects import *  # noqa F403
else:
       from .pipelines import (
           OnnxStableDiffusionImgaImgPipeline,
           OnnxStableDiffusionInpaintPipeline,
           OnnxStableDiffusionInpaintPipelineLegacy,
           OnnxStableDiffusionPipeline,
           OnnxStableDiffusionUpscalePipeline,
           StableDiffusionOnnxPipeline,
       )

try:
       if not (is_torch_available() and is_librosa_available()):
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       from .utils.dummy_torch_and_librosa_objects import *  # noqa F403
else:
       from .pipelines import AudioDiffusionPipeline, Mel

try:
       if not (is_transformers_available() and is_torch_available() and is_note_seq_available()):
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       from .utils.dummy_transformers_and_torch_and_note_seq_objects import *  # noqa F403
else:
       from .pipelines import SpectrogramDiffusionPipeline

try:
       if not is_flax_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       from .utils.dummy_flax_objects import *  # noqa F403
else:
       from .models.controlnet_flax import FlaxControlNetModel
       from .models.modeling_flax_utils import FlaxModelMixin
       from .models.unet_ad_condition_flax import FlaxUNetaDConditionModel
       from .models.vae_flax import FlaxAutoencoderKL
       from .pipelines import FlaxDiffusionPipeline
       from .schedulers import (
           FlaxDDIMScheduler,
           FlaxDDPMScheduler,
           FlaxDPMSolverMultistepScheduler,
           FlaxKarrasVeScheduler,
           FlaxLMSDiscreteScheduler,
           FlaxPNDMScheduler,
           FlaxSchedulerMixin,
           FlaxScoreSdeVeScheduler,
       )


try:
       if not (is_flax_available() and is_transformers_available()):
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       from .utils.dummy_flax_and_transformers_objects import *  # noqa F403
else:
       from .pipelines import (
           FlaxStableDiffusionControlNetPipeline,
           FlaxStableDiffusionImgaImgPipeline,
           FlaxStableDiffusionInpaintPipeline,
           FlaxStableDiffusionPipeline,
       )

try:
       if not (is_note_seq_available()):
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       from .utils.dummy_note_seq_objects import *  # noqa F403
else:
       from .pipelines import MidiProcessor













from typing import Any, Dict, List, Union

from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends
from .base import PIPELINE_INIT_ARGS, ChunkPipeline


if is_vision_available():
       from PIL import Image

       from ..image_utils import load_image

if is_torch_available():
       import torch

       from transformers.modeling_outputs import BaseModelOutput

       from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING

__lowerCamelCase	:		Dict										=   logging.get_logger(__name__)







@add_end_docstrings(_A						)
class  _lowercase   (   _A						):
      def __init__(     self				,			**a   ):
       super().__init__(**a   )

       if self.framework == "tf":
        raise ValueError(F"The {self.__class__} is only available in PyTorch."   )

       requires_backends(self				,			"""vision"""   )
       self.check_model_type(a   )
      def __call__(     self				,			a				,			a = None				,			**a				,			):
       if "text_queries" in kwargs:
        snake_case__  :    Any							       =kwargs.pop("""text_queries"""   )

       if isinstance(a				,			(str, Image.Image)   ):
        snake_case__  :    Union[str, Any]							       ={"""image""": image, """candidate_labels""": candidate_labels}
       else:
        snake_case__  :    str							       =image
       snake_case__  :    Union[str, Any]							       =super().__call__(a				,			**a   )
       return results
      def 						lowercase__					(     self				,			**a   ):
       snake_case__  :    Union[str, Any]							       ={}
       if "threshold" in kwargs:
        snake_case__  :    Optional[Any]							       =kwargs["""threshold"""]
       if "top_k" in kwargs:
        snake_case__  :    Dict							       =kwargs["""top_k"""]
       return {}, {}, postprocess_params
      def 						lowercase__					(     self				,			a   ):
       snake_case__  :    List[Any]							       =load_image(inputs["""image"""]   )
       snake_case__  :    Dict							       =inputs["""candidate_labels"""]
       if isinstance(a				,			a   ):
        snake_case__  :    str							       =candidate_labels.split(""","""   )

       snake_case__  :    Optional[Any]							       =torch.tensor([[image.height, image.width]]				,			dtype=torch.intaa   )
       for i, candidate_label in enumerate(a   ):
        snake_case__  :    Tuple							       =self.tokenizer(a				,			return_tensors=self.framework   )
        snake_case__  :    int							       =self.image_processor(a				,			return_tensors=self.framework   )
        yield {
            "is_last": i == len(a   ) - 1,
            "target_size": target_size,
            "candidate_label": candidate_label,
            **text_inputs,
            **image_features,
        }
      def 						lowercase__					(     self				,			a   ):
       snake_case__  :    Tuple							       =model_inputs.pop("""target_size"""   )
       snake_case__  :    Tuple							       =model_inputs.pop("""candidate_label"""   )
       snake_case__  :    Dict							       =model_inputs.pop("""is_last"""   )

       snake_case__  :    Any							       =self.model(**a   )

       snake_case__  :    List[Any]							       ={"""target_size""": target_size, """candidate_label""": candidate_label, """is_last""": is_last, **outputs}
       return model_outputs
      def 						lowercase__					(     self				,			a				,			a=0.1				,			a=None   ):
       snake_case__  :    Optional[int]							       =[]
       for model_output in model_outputs:
        snake_case__  :    Tuple							       =model_output["""candidate_label"""]
        snake_case__  :    Optional[int]							       =BaseModelOutput(a   )
        snake_case__  :    int							       =self.image_processor.post_process_object_detection(
            outputs=a				,			threshold=a				,			target_sizes=model_output["""target_size"""]   )[0]

        for index in outputs["scores"].nonzero():
         snake_case__  :    int							       =outputs["""scores"""][index].item()
         snake_case__  :    Tuple							       =self._get_bounding_box(outputs["""boxes"""][index][0]   )

         snake_case__  :    Tuple							       ={"""score""": score, """label""": label, """box""": box}
         results.append(a   )

       snake_case__  :    Tuple							       =sorted(a				,			key=lambda a   : x["score"]				,			reverse=a   )
       if top_k:
        snake_case__  :    Union[str, Any]							       =results[:top_k]

       return results



      def 						lowercase__					(     self				,			a   ):
       if self.framework != "pt":
        raise ValueError("""The ZeroShotObjectDetectionPipeline is only available in PyTorch."""   )
       snake_case__       ,   snake_case__       ,   snake_case__       ,   snake_case__  :    Dict							       =box.int().tolist()
       snake_case__  :    int							       ={
           """xmin""": xmin,
           """ymin""": ymin,
           """xmax""": xmax,
           """ymax""": ymax,
       }
       return bbox





