






a_							=			'''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










'''simple docstring'''







from typing import Dict, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image
from ...image_utils import (
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends


if is_vision_available():
   import PIL

# soft dependency
if is_pytesseract_available():
   import pytesseract

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


def 	SCREAMING_SNAKE_CASE_					(  _UpperCAmelCase	:	str    ,_UpperCAmelCase	:	Tuple    ,_UpperCAmelCase	:	List[str]  )  ->			int:
       return [
           int(1000 * (box[0] / width)  ),
           int(1000 * (box[1] / height)  ),
           int(1000 * (box[2] / width)  ),
           int(1000 * (box[3] / height)  ),
       ]


def 	SCREAMING_SNAKE_CASE_					(  _UpperCAmelCase	:	np.ndarray    ,_UpperCAmelCase	:	Optional[str]    ,_UpperCAmelCase	:	Optional[str] = None  )  ->			Optional[int]:
       _a    : Any     					=tesseract_config if tesseract_config is not None else """"""

       # apply OCR
       _a    : Optional[Any]     					=to_pil_image(_UpperCAmelCase  )
       _a					,    _a    : List[Any]     					=pil_image.size
       _a    : List[str]     					=pytesseract.image_to_data(_UpperCAmelCase    ,lang=_UpperCAmelCase    ,output_type="""dict"""    ,config=_UpperCAmelCase  )
       _a					,    _a					,    _a					,    _a					,    _a    : str     					=data["""text"""], data["""left"""], data["""top"""], data["""width"""], data["""height"""]

       # filter empty words and corresponding coordinates
       _a    : Tuple     					=[idx for idx, word in enumerate(_UpperCAmelCase  ) if not word.strip()]
       _a    : List[Any]     					=[word for idx, word in enumerate(_UpperCAmelCase  ) if idx not in irrelevant_indices]
       _a    : Dict     					=[coord for idx, coord in enumerate(_UpperCAmelCase  ) if idx not in irrelevant_indices]
       _a    : List[str]     					=[coord for idx, coord in enumerate(_UpperCAmelCase  ) if idx not in irrelevant_indices]
       _a    : Union[str, Any]     					=[coord for idx, coord in enumerate(_UpperCAmelCase  ) if idx not in irrelevant_indices]
       _a    : Union[str, Any]     					=[coord for idx, coord in enumerate(_UpperCAmelCase  ) if idx not in irrelevant_indices]

       # turn coordinates into (left, top, left+width, top+height) format
       _a    : List[str]     					=[]
       for x, y, w, h in zip(_UpperCAmelCase    ,_UpperCAmelCase    ,_UpperCAmelCase    ,_UpperCAmelCase  ):
              _a    : int     					=[x, y, x + w, y + h]
              actual_boxes.append(_UpperCAmelCase  )

       # finally, normalize the bounding boxes
       _a    : str     					=[]
       for box in actual_boxes:
              normalized_boxes.append(normalize_box(_UpperCAmelCase    ,_UpperCAmelCase    ,_UpperCAmelCase  )  )

       assert len(_UpperCAmelCase  ) == len(_UpperCAmelCase  ), "Not as many words as there are bounding boxes"

       return words, normalized_boxes







class A__       (						UpperCAmelCase__      ):
      __UpperCamelCase       :  List[Any]	       =							["pixel_values"]






      def __init__( self			:Tuple     ,						SCREAMING_SNAKE_CASE			:bool = True     ,						SCREAMING_SNAKE_CASE			:Dict[str, int] = None     ,						SCREAMING_SNAKE_CASE			:PILImageResampling = PILImageResampling.BILINEAR     ,						SCREAMING_SNAKE_CASE			:bool = True     ,						SCREAMING_SNAKE_CASE			:Optional[str] = None     ,						SCREAMING_SNAKE_CASE			:Optional[str] = ""     ,						**SCREAMING_SNAKE_CASE			:Tuple     ,						)       ->					None:




             '''simple docstring'''
             super().__init__(**SCREAMING_SNAKE_CASE	)
             _a    : List[Any]     					=size if size is not None else {"""height""": 2_2_4, """width""": 2_2_4}
             _a    : Tuple     					=get_size_dict(SCREAMING_SNAKE_CASE	)

             _a    : Dict     					=do_resize
             _a    : Tuple     					=size
             _a    : str     					=resample
             _a    : Dict     					=apply_ocr
             _a    : Union[str, Any]     					=ocr_lang
             _a    : Dict     					=tesseract_config






      def __UpperCAmelCase       ( self			:List[str]     ,						SCREAMING_SNAKE_CASE			:np.ndarray     ,						SCREAMING_SNAKE_CASE			:Dict[str, int]     ,						SCREAMING_SNAKE_CASE			:PILImageResampling = PILImageResampling.BILINEAR     ,						SCREAMING_SNAKE_CASE			:Optional[Union[str, ChannelDimension]] = None     ,						**SCREAMING_SNAKE_CASE			:Dict     ,						)       ->					np.ndarray:




             '''simple docstring'''
             _a    : int     					=get_size_dict(SCREAMING_SNAKE_CASE	)
             if "height" not in size or "width" not in size:
                    raise ValueError(f"The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}"	)
             _a    : Any     					=(size["""height"""], size["""width"""])
             return resize(SCREAMING_SNAKE_CASE     ,						size=SCREAMING_SNAKE_CASE     ,						resample=SCREAMING_SNAKE_CASE     ,						data_format=SCREAMING_SNAKE_CASE     ,						**SCREAMING_SNAKE_CASE	)






      def __UpperCAmelCase       ( self			:Dict     ,						SCREAMING_SNAKE_CASE			:ImageInput     ,						SCREAMING_SNAKE_CASE			:bool = None     ,						SCREAMING_SNAKE_CASE			:Dict[str, int] = None     ,						SCREAMING_SNAKE_CASE			:PILImageResampling = None     ,						SCREAMING_SNAKE_CASE			:bool = None     ,						SCREAMING_SNAKE_CASE			:Optional[str] = None     ,						SCREAMING_SNAKE_CASE			:Optional[str] = None     ,						SCREAMING_SNAKE_CASE			:Optional[Union[str, TensorType]] = None     ,						SCREAMING_SNAKE_CASE			:ChannelDimension = ChannelDimension.FIRST     ,						**SCREAMING_SNAKE_CASE			:Optional[Any]     ,						)       ->					PIL.Image.Image:




             '''simple docstring'''
             _a    : Optional[int]     					=do_resize if do_resize is not None else self.do_resize
             _a    : Optional[int]     					=size if size is not None else self.size
             _a    : str     					=get_size_dict(SCREAMING_SNAKE_CASE	)
             _a    : List[str]     					=resample if resample is not None else self.resample
             _a    : int     					=apply_ocr if apply_ocr is not None else self.apply_ocr
             _a    : str     					=ocr_lang if ocr_lang is not None else self.ocr_lang
             _a    : Union[str, Any]     					=tesseract_config if tesseract_config is not None else self.tesseract_config

             _a    : List[str]     					=make_list_of_images(SCREAMING_SNAKE_CASE	)

             if not valid_images(SCREAMING_SNAKE_CASE	):
                    raise ValueError(
                        """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
                        """torch.Tensor, tf.Tensor or jax.ndarray."""	)

             if do_resize and size is None:
                    raise ValueError("""Size must be specified if do_resize is True."""	)

             # All transformations expect numpy arrays.
             _a    : List[Any]     					=[to_numpy_array(SCREAMING_SNAKE_CASE	) for image in images]

             if apply_ocr:
                    requires_backends(self     ,						"""pytesseract"""	)
                    _a    : Any     					=[]
                    _a    : Any     					=[]
                    for image in images:
                           _a					,    _a    : int     					=apply_tesseract(SCREAMING_SNAKE_CASE     ,						SCREAMING_SNAKE_CASE     ,						SCREAMING_SNAKE_CASE	)
                           words_batch.append(SCREAMING_SNAKE_CASE	)
                           boxes_batch.append(SCREAMING_SNAKE_CASE	)

             if do_resize:
                    _a    : Union[str, Any]     					=[self.resize(image=SCREAMING_SNAKE_CASE     ,						size=SCREAMING_SNAKE_CASE     ,						resample=SCREAMING_SNAKE_CASE	) for image in images]

             # flip color channels from RGB to BGR (as Detectron2 requires this)
             _a    : Dict     					=[flip_channel_order(SCREAMING_SNAKE_CASE	) for image in images]
             _a    : str     					=[to_channel_dimension_format(SCREAMING_SNAKE_CASE     ,						SCREAMING_SNAKE_CASE	) for image in images]

             _a    : str     					=BatchFeature(data={"""pixel_values""": images}     ,						tensor_type=SCREAMING_SNAKE_CASE	)

             if apply_ocr:
                    _a    : List[Any]     					=words_batch
                    _a    : Dict     					=boxes_batch
             return data


