






"""simple docstring"""





import random
import unittest

import numpy as np
import torch

from diffusers import DDIMScheduler, LDMSuperResolutionPipeline, UNetaDModel, VQModel
from diffusers.utils import PIL_INTERPOLATION, floats_tensor, load_image, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch


enable_full_determinism()







class 		_a       (						unittest.TestCase   ):





   '''simple docstring'''






   @property
   def __lowercase    (   self)	-> Any:




          '''simple docstring'''




          lowercase__:    Optional[Any]        =      1
          lowercase__:    Dict        =      3
          lowercase__:    Optional[Any]        =      (32, 32)

          lowercase__:    int        =      floats_tensor((batch_size, num_channels) + sizes			,				rng=random.Random(0)).to(UpperCAmelCase_)
          return image





   @property
   def __lowercase    (   self)	-> Tuple:




          '''simple docstring'''




          torch.manual_seed(0)
          lowercase__:    Optional[int]        =      UNetaDModel(
              block_out_channels=(32, 64)			,				layers_per_block=2			,				sample_size=32			,				in_channels=6			,				out_channels=3			,				down_block_types=("DownBlock2D", "AttnDownBlock2D")			,				up_block_types=("AttnUpBlock2D", "UpBlock2D")			,				)
          return model





   @property
   def __lowercase    (   self)	-> int:




          '''simple docstring'''




          torch.manual_seed(0)
          lowercase__:    str        =      VQModel(
              block_out_channels=[32, 64]			,				in_channels=3			,				out_channels=3			,				down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"]			,				up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"]			,				latent_channels=3			,				)
          return model





   def __lowercase    (   self)	-> Optional[Any]:




          '''simple docstring'''




          lowercase__:    Optional[int]        =      "cpu"
          lowercase__:    List[Any]        =      self.dummy_uncond_unet
          lowercase__:    Tuple        =      DDIMScheduler()
          lowercase__:    Optional[Any]        =      self.dummy_vq_model

          lowercase__:    Optional[int]        =      LDMSuperResolutionPipeline(unet=UpperCAmelCase_			,				vqvae=UpperCAmelCase_			,				scheduler=UpperCAmelCase_)
          ldm.to(UpperCAmelCase_)
          ldm.set_progress_bar_config(disable=UpperCAmelCase_)

          lowercase__:    Union[str, Any]        =      self.dummy_image.to(UpperCAmelCase_)

          lowercase__:    List[str]        =      torch.Generator(device=UpperCAmelCase_).manual_seed(0)
          lowercase__:    Tuple        =      ldm(image=UpperCAmelCase_			,				generator=UpperCAmelCase_			,				num_inference_steps=2			,				output_type="numpy").images

          lowercase__:    Tuple        =      image[0, -3:, -3:, -1]

          assert image.shape == (1, 64, 64, 3)
          lowercase__:    Union[str, Any]        =      np.array([0.86_78, 0.82_45, 0.63_81, 0.68_30, 0.43_85, 0.55_99, 0.46_41, 0.62_01, 0.51_50])

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





   @unittest.skipIf(torch_device != "cuda"			,				"This test requires a GPU")
   def __lowercase    (   self)	-> List[str]:




          '''simple docstring'''




          lowercase__:    Dict        =      self.dummy_uncond_unet
          lowercase__:    Optional[Any]        =      DDIMScheduler()
          lowercase__:    List[str]        =      self.dummy_vq_model

          # put models in fp16
          lowercase__:    Optional[int]        =      unet.half()
          lowercase__:    Union[str, Any]        =      vqvae.half()

          lowercase__:    Any        =      LDMSuperResolutionPipeline(unet=UpperCAmelCase_			,				vqvae=UpperCAmelCase_			,				scheduler=UpperCAmelCase_)
          ldm.to(UpperCAmelCase_)
          ldm.set_progress_bar_config(disable=UpperCAmelCase_)

          lowercase__:    Dict        =      self.dummy_image.to(UpperCAmelCase_)

          lowercase__:    Any        =      ldm(UpperCAmelCase_			,				num_inference_steps=2			,				output_type="numpy").images

          assert image.shape == (1, 64, 64, 3)







@slow
@require_torch
class 		_a       (						unittest.TestCase   ):





   '''simple docstring'''






   def __lowercase    (   self)	-> List[Any]:




          '''simple docstring'''




          lowercase__:    Tuple        =      load_image(
              "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
              "/vq_diffusion/teddy_bear_pool.png")
          lowercase__:    Union[str, Any]        =      init_image.resize((64, 64)			,				resample=PIL_INTERPOLATION["lanczos"])

          lowercase__:    Dict        =      LDMSuperResolutionPipeline.from_pretrained("duongna/ldm-super-resolution"			,				device_map="auto")
          ldm.set_progress_bar_config(disable=UpperCAmelCase_)

          lowercase__:    Union[str, Any]        =      torch.manual_seed(0)
          lowercase__:    List[str]        =      ldm(image=UpperCAmelCase_			,				generator=UpperCAmelCase_			,				num_inference_steps=20			,				output_type="numpy").images

          lowercase__:    List[str]        =      image[0, -3:, -3:, -1]

          assert image.shape == (1, 256, 256, 3)
          lowercase__:    List[Any]        =      np.array([0.76_44, 0.76_79, 0.76_42, 0.76_33, 0.76_66, 0.75_60, 0.74_25, 0.72_57, 0.69_07])

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














"""simple docstring"""





# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

from ..utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_torch_available,
)


UpperCamelCase			=      {
    """agents""": ["""Agent""", """AzureOpenAiAgent""", """HfAgent""", """LocalAgent""", """OpenAiAgent"""],
    """base""": ["""PipelineTool""", """RemoteTool""", """Tool""", """launch_gradio_demo""", """load_tool"""],
}

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  UpperCamelCase			=      ["""DocumentQuestionAnsweringTool"""]
  UpperCamelCase			=      ["""ImageCaptioningTool"""]
  UpperCamelCase			=      ["""ImageQuestionAnsweringTool"""]
  UpperCamelCase			=      ["""ImageSegmentationTool"""]
  UpperCamelCase			=      ["""SpeechToTextTool"""]
  UpperCamelCase			=      ["""TextClassificationTool"""]
  UpperCamelCase			=      ["""TextQuestionAnsweringTool"""]
  UpperCamelCase			=      ["""TextSummarizationTool"""]
  UpperCamelCase			=      ["""TextToSpeechTool"""]
  UpperCamelCase			=      ["""TranslationTool"""]

if TYPE_CHECKING:
  from .agents import Agent, AzureOpenAiAgent, HfAgent, LocalAgent, OpenAiAgent
  from .base import PipelineTool, RemoteTool, Tool, launch_gradio_demo, load_tool

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .document_question_answering import DocumentQuestionAnsweringTool
    from .image_captioning import ImageCaptioningTool
    from .image_question_answering import ImageQuestionAnsweringTool
    from .image_segmentation import ImageSegmentationTool
    from .speech_to_text import SpeechToTextTool
    from .text_classification import TextClassificationTool
    from .text_question_answering import TextQuestionAnsweringTool
    from .text_summarization import TextSummarizationTool
    from .text_to_speech import TextToSpeechTool
    from .translation import TranslationTool
else:
  import sys

  UpperCamelCase			=      _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)






