'''simple docstring'''
import importlib
import inspect
from functools import wraps
from typing import TYPE_CHECKING, Optional, Union

from .download.streaming_download_manager import (
    xbasename,
    xdirname,
    xet_parse,
    xexists,
    xgetsize,
    xglob,
    xgzip_open,
    xisdir,
    xisfile,
    xjoin,
    xlistdir,
    xnumpy_load,
    xopen,
    xpandas_read_csv,
    xpandas_read_excel,
    xPath,
    xrelpath,
    xsio_loadmat,
    xsplit,
    xsplitext,
    xwalk,
    xxml_dom_minidom_parse,
)
from .utils.logging import get_logger
from .utils.patching import patch_submodule
from .utils.py_utils import get_imports


_A		:      str						   =get_logger(__name__)


if TYPE_CHECKING:
 from .builder import DatasetBuilder







def 				__UpperCamelCase (					__UpperCAmelCase  :					Dict ,   __UpperCAmelCase  :					Optional[Union[str, bool]] = None			)							->	Dict:
  lowercase				:							Any									=   importlib.import_module(_a			)

  # TODO(QL): always update the module to add subsequent new authentication
  if hasattr(_a ,   '''_patched_for_streaming'''			) and module._patched_for_streaming:
    return

  def wrap_auth(__UpperCAmelCase  :					str			):
    @wraps(_a			)
    def wrapper(*__UpperCAmelCase  :					Dict ,   **__UpperCAmelCase  :					Dict			):
      return function(*_a ,   use_auth_token=_a ,   **_a			)

    lowercase				:							Tuple									=   'wrap_auth'
    return wrapper

  # open files in a streaming fashion
  patch_submodule(_a ,   '''open''' ,   wrap_auth(_a			)			).start()
  patch_submodule(_a ,   '''os.listdir''' ,   wrap_auth(_a			)			).start()
  patch_submodule(_a ,   '''os.walk''' ,   wrap_auth(_a			)			).start()
  patch_submodule(_a ,   '''glob.glob''' ,   wrap_auth(_a			)			).start()
  # allow to navigate in remote zip files
  patch_submodule(_a ,   '''os.path.join''' ,   _a			).start()
  patch_submodule(_a ,   '''os.path.dirname''' ,   _a			).start()
  patch_submodule(_a ,   '''os.path.basename''' ,   _a			).start()
  patch_submodule(_a ,   '''os.path.relpath''' ,   _a			).start()
  patch_submodule(_a ,   '''os.path.split''' ,   _a			).start()
  patch_submodule(_a ,   '''os.path.splitext''' ,   _a			).start()
  # allow checks on paths
  patch_submodule(_a ,   '''os.path.exists''' ,   wrap_auth(_a			)			).start()
  patch_submodule(_a ,   '''os.path.isdir''' ,   wrap_auth(_a			)			).start()
  patch_submodule(_a ,   '''os.path.isfile''' ,   wrap_auth(_a			)			).start()
  patch_submodule(_a ,   '''os.path.getsize''' ,   wrap_auth(_a			)			).start()
  patch_submodule(_a ,   '''pathlib.Path''' ,   _a			).start()
  # file readers
  patch_submodule(_a ,   '''gzip.open''' ,   wrap_auth(_a			)			).start()
  patch_submodule(_a ,   '''numpy.load''' ,   wrap_auth(_a			)			).start()
  patch_submodule(_a ,   '''pandas.read_csv''' ,   wrap_auth(_a			) ,   attrs=['''__version__''']			).start()
  patch_submodule(_a ,   '''pandas.read_excel''' ,   wrap_auth(_a			) ,   attrs=['''__version__''']			).start()
  patch_submodule(_a ,   '''scipy.io.loadmat''' ,   wrap_auth(_a			) ,   attrs=['''__version__''']			).start()
  patch_submodule(_a ,   '''xml.etree.ElementTree.parse''' ,   wrap_auth(_a			)			).start()
  patch_submodule(_a ,   '''xml.dom.minidom.parse''' ,   wrap_auth(_a			)			).start()
  lowercase				:							List[str]									=   True







def 				__UpperCamelCase (					__UpperCAmelCase  :					"DatasetBuilder"			)							->	Optional[int]:
  extend_module_for_streaming(builder.__module__ ,   use_auth_token=builder.use_auth_token			)
  # if needed, we also have to extend additional internal imports (like wmt14 -> wmt_utils)
  if not builder.__module__.startswith('''datasets.'''			):  # check that it's not a packaged builder like csv
    for imports in get_imports(inspect.getfile(builder.__class__			)			):
      if imports[0] == "internal":
        lowercase				:							Any									=   imports[1]
        lowercase				:							Any									=   '.'.join(builder.__module__.split('''.'''			)[:-1] + [internal_import_name]			)
        extend_module_for_streaming(_a ,   use_auth_token=builder.use_auth_token			)

    # builders can inherit from other builders that might use streaming functionality
    # (for example, ImageFolder and AudioFolder inherit from FolderBuilder which implements examples generation)
    # but these parents builders are not patched automatically as they are not instantiated, so we patch them here
  from .builder import DatasetBuilder

  lowercase				:							Optional[int]									=   [
      cls.__module__
      for cls in type(_a			).__mro__[1:]  # make sure it's not the same module we've already patched
      if issubclass(cls ,   _a			) and cls.__module__ != DatasetBuilder.__module__
  ]  # check it's not a standard builder from datasets.builder
  for module in parent_builder_modules:
    extend_module_for_streaming(_a ,   use_auth_token=builder.use_auth_token			)
'''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       __lowercase		(    unittest.TestCase    ):







     """simple docstring"""






     @property
     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Dict		     =	1
         __UpperCamelCase						:						Union[str, Any]		     =	3
         __UpperCamelCase						:						Tuple		     =	(3_2, 3_2)

         __UpperCamelCase						:						List[Any]		     =	floats_tensor((batch_size, num_channels) + sizes  ,      rng=random.Random(0     )     ).to(_lowerCamelCase     )
         return image







     @property
     def lowerCAmelCase  (		self     ):
         torch.manual_seed(0     )
         __UpperCamelCase						:						Dict		     =	UNetaDModel(
             block_out_channels=(3_2, 6_4)  ,      layers_per_block=2  ,      sample_size=3_2  ,      in_channels=6  ,      out_channels=3  ,      down_block_types=('DownBlock2D', 'AttnDownBlock2D')  ,      up_block_types=('AttnUpBlock2D', 'UpBlock2D')  ,      )
         return model







     @property
     def lowerCAmelCase  (		self     ):
         torch.manual_seed(0     )
         __UpperCamelCase						:						List[str]		     =	VQModel(
             block_out_channels=[3_2, 6_4]  ,      in_channels=3  ,      out_channels=3  ,      down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']  ,      up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']  ,      latent_channels=3  ,      )
         return model







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Tuple		     =	'cpu'
         __UpperCamelCase						:						Union[str, Any]		     =	self.dummy_uncond_unet
         __UpperCamelCase						:						List[str]		     =	DDIMScheduler()
         __UpperCamelCase						:						Any		     =	self.dummy_vq_model

         __UpperCamelCase						:						Tuple		     =	LDMSuperResolutionPipeline(unet=_lowerCamelCase  ,      vqvae=_lowerCamelCase  ,      scheduler=_lowerCamelCase     )
         ldm.to(_lowerCamelCase     )
         ldm.set_progress_bar_config(disable=_lowerCamelCase     )

         __UpperCamelCase						:						int		     =	self.dummy_image.to(_lowerCamelCase     )

         __UpperCamelCase						:						Union[str, Any]		     =	torch.Generator(device=_lowerCamelCase     ).manual_seed(0     )
         __UpperCamelCase						:						Union[str, Any]		     =	ldm(image=_lowerCamelCase  ,      generator=_lowerCamelCase  ,      num_inference_steps=2  ,      output_type='numpy'     ).images

         __UpperCamelCase						:						str		     =	image[0, -3:, -3:, -1]

         assert image.shape == (1, 6_4, 6_4, 3)
         __UpperCamelCase						:						str		     =	np.array([0.8_6_7_8, 0.8_2_4_5, 0.6_3_8_1, 0.6_8_3_0, 0.4_3_8_5, 0.5_5_9_9, 0.4_6_4_1, 0.6_2_0_1, 0.5_1_5_0]     )

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







     @unittest.skipIf(torch_device != 'cuda'  ,      'This test requires a GPU'     )
     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Optional[Any]		     =	self.dummy_uncond_unet
         __UpperCamelCase						:						Optional[int]		     =	DDIMScheduler()
         __UpperCamelCase						:						Any		     =	self.dummy_vq_model

         # put models in fp16
         __UpperCamelCase						:						str		     =	unet.half()
         __UpperCamelCase						:						Optional[Any]		     =	vqvae.half()

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

         __UpperCamelCase						:						Dict		     =	self.dummy_image.to(_lowerCamelCase     )

         __UpperCamelCase						:						Optional[Any]		     =	ldm(_lowerCamelCase  ,      num_inference_steps=2  ,      output_type='numpy'     ).images

         assert image.shape == (1, 6_4, 6_4, 3)






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







     """simple docstring"""






     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						List[Any]		     =	load_image(
             'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
             '/vq_diffusion/teddy_bear_pool.png'     )
         __UpperCamelCase						:						List[Any]		     =	init_image.resize((6_4, 6_4)  ,      resample=PIL_INTERPOLATION['lanczos']     )

         __UpperCamelCase						:						List[str]		     =	LDMSuperResolutionPipeline.from_pretrained('duongna/ldm-super-resolution'  ,      device_map='auto'     )
         ldm.set_progress_bar_config(disable=_lowerCamelCase     )

         __UpperCamelCase						:						Union[str, Any]		     =	torch.manual_seed(0     )
         __UpperCamelCase						:						Dict		     =	ldm(image=_lowerCamelCase  ,      generator=_lowerCamelCase  ,      num_inference_steps=2_0  ,      output_type='numpy'     ).images

         __UpperCamelCase						:						List[Any]		     =	image[0, -3:, -3:, -1]

         assert image.shape == (1, 2_5_6, 2_5_6, 3)
         __UpperCamelCase						:						str		     =	np.array([0.7_6_4_4, 0.7_6_7_9, 0.7_6_4_2, 0.7_6_3_3, 0.7_6_6_6, 0.7_5_6_0, 0.7_4_2_5, 0.7_2_5_7, 0.6_9_0_7]     )

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



