


"""simple docstring"""







import random
import unittest

import torch

from diffusers import IFImgaImgSuperResolutionPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin


@skip_mps
class 				SCREAMING_SNAKE_CASE__    (		lowercase       ,   lowercase       ,   unittest.TestCase    ):
       """simple docstring"""


       a  :    Any       =IFImgaImgSuperResolutionPipeline
       a  :    int       =TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"width", "height"}
       a  :    Any       =TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"original_image"}    )
       a  :    Union[str, Any]       =PipelineTesterMixin.required_optional_params - {"latents"}

       def 	lowercase__							(						self						):






         """simple docstring"""





         return self._get_superresolution_dummy_components()

       def 	lowercase__							(						self		,					snake_case__		,					snake_case__=0						):






         """simple docstring"""





         if str(snake_case__						).startswith("mps"						):
           lowerCAmelCase					:					int								=							torch.manual_seed(snake_case__						)
         else:
           lowerCAmelCase					:					int								=							torch.Generator(device=snake_case__						).manual_seed(snake_case__						)

         lowerCAmelCase					:					List[Any]								=							floats_tensor((1, 3, 32, 32)		,					rng=random.Random(snake_case__						)						).to(snake_case__						)
         lowerCAmelCase					:					Optional[Any]								=							floats_tensor((1, 3, 16, 16)		,					rng=random.Random(snake_case__						)						).to(snake_case__						)

         lowerCAmelCase					:					List[Any]								=							{
             "prompt": "A painting of a squirrel eating a burger",
             "image": image,
             "original_image": original_image,
             "generator": generator,
             "num_inference_steps": 2,
             "output_type": "numpy",
         }

         return inputs

       @unittest.skipIf(
           torch_device != "cuda" or not is_xformers_available()		,					reason="XFormers attention is only available with CUDA and `xformers` installed"		,					)
       def 	lowercase__							(						self						):






         """simple docstring"""





         self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3						)

       def 	lowercase__							(						self						):






         """simple docstring"""





         self._test_save_load_optional_components()

       @unittest.skipIf(torch_device != "cuda"		,					reason="float16 requires CUDA"						)
       def 	lowercase__							(						self						):






         """simple docstring"""





         super().test_save_load_floataa(expected_max_diff=1e-1						)

       def 	lowercase__							(						self						):






         """simple docstring"""





         self._test_attention_slicing_forward_pass(expected_max_diff=1e-2						)

       def 	lowercase__							(						self						):






         """simple docstring"""





         self._test_save_load_local()







       def 	lowercase__							(						self						):






         """simple docstring"""





         self._test_inference_batch_single_identical(
             expected_max_diff=1e-2		,					)









"""simple docstring"""







import multiprocessing
from typing import TYPE_CHECKING, Optional, Union

from .. import Dataset, Features, config
from ..formatting import query_table
from ..packaged_modules.sql.sql import Sql
from ..utils import logging
from .abc import AbstractDatasetInputStream


if TYPE_CHECKING:
     import sqlitea

     import sqlalchemy


class 				SCREAMING_SNAKE_CASE__    (		lowercase    ):
       """simple docstring"""


       def __init__(						self		,					snake_case__		,					snake_case__		,					snake_case__ = None		,					snake_case__ = None		,					snake_case__ = False		,					**snake_case__		,					):






         """simple docstring"""





         super().__init__(features=snake_case__		,					cache_dir=snake_case__		,					keep_in_memory=snake_case__		,					**snake_case__						)
         lowerCAmelCase					:					Dict								=							Sql(
             cache_dir=snake_case__		,					features=snake_case__		,					sql=snake_case__		,					con=snake_case__		,					**snake_case__		,					)







       def 	lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase					:					Tuple								=							None
         lowerCAmelCase					:					Optional[int]								=							None
         lowerCAmelCase					:					str								=							None
         lowerCAmelCase					:					int								=							None

         self.builder.download_and_prepare(
             download_config=snake_case__		,					download_mode=snake_case__		,					verification_mode=snake_case__		,					base_path=snake_case__		,					)

         # Build dataset for splits
         lowerCAmelCase					:					str								=							self.builder.as_dataset(
             split="train"		,					verification_mode=snake_case__		,					in_memory=self.keep_in_memory						)
         return dataset


class 				SCREAMING_SNAKE_CASE__    :
       """simple docstring"""


       def __init__(						self		,					snake_case__		,					snake_case__		,					snake_case__		,					snake_case__ = None		,					snake_case__ = None		,					**snake_case__		,					):






         """simple docstring"""





         if num_proc is not None and num_proc <= 0:
           raise ValueError(f"""num_proc {num_proc} must be an integer > 0."""						)

         lowerCAmelCase					:					Tuple								=							dataset
         lowerCAmelCase					:					Tuple								=							name
         lowerCAmelCase					:					List[str]								=							con
         lowerCAmelCase					:					List[Any]								=							batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE
         lowerCAmelCase					:					Optional[int]								=							num_proc
         lowerCAmelCase					:					Optional[int]								=							to_sql_kwargs

       def 	lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase					:					List[str]								=							self.to_sql_kwargs.pop("sql"		,					snake_case__						)
         lowerCAmelCase					:					List[Any]								=							self.to_sql_kwargs.pop("con"		,					snake_case__						)
         lowerCAmelCase					:					Dict								=							self.to_sql_kwargs.pop("index"		,					snake_case__						)

         lowerCAmelCase					:					Dict								=							self._write(index=snake_case__		,					**self.to_sql_kwargs						)
         return written

       def 	lowercase__							(						self		,					snake_case__						):






         """simple docstring"""





         lowerCAmelCase						,  lowerCAmelCase						,  lowerCAmelCase					:					Optional[int]								=							args
         lowerCAmelCase					:					Optional[int]								=							{**to_sql_kwargs, "if_exists": "append"} if offset > 0 else to_sql_kwargs
         lowerCAmelCase					:					List[Any]								=							query_table(
             table=self.dataset.data		,					key=slice(snake_case__		,					offset + self.batch_size						)		,					indices=self.dataset._indices		,					)
         lowerCAmelCase					:					Tuple								=							batch.to_pandas()
         lowerCAmelCase					:					str								=							df.to_sql(self.name		,					self.con		,					index=snake_case__		,					**snake_case__						)
         return num_rows or len(snake_case__						)







       def 	lowercase__							(						self		,					snake_case__		,					**snake_case__						):






         """simple docstring"""





         lowerCAmelCase					:					Tuple								=							0

         if self.num_proc is None or self.num_proc == 1:
           for offset in logging.tqdm(
               range(0		,					len(self.dataset						)		,					self.batch_size						)		,					unit="ba"		,					disable=not logging.is_progress_bar_enabled()		,					desc="Creating SQL from Arrow format"		,					):
             written += self._batch_sql((offset, index, to_sql_kwargs)						)
         else:
           lowerCAmelCase						,  lowerCAmelCase					:					Dict								=							len(self.dataset						), self.batch_size
           with multiprocessing.Pool(self.num_proc						) as pool:
             for num_rows in logging.tqdm(
                 pool.imap(
                     self._batch_sql		,					[(offset, index, to_sql_kwargs) for offset in range(0		,					snake_case__		,					snake_case__						)]		,					)		,					total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size		,					unit="ba"		,					disable=not logging.is_progress_bar_enabled()		,					desc="Creating SQL from Arrow format"		,					):
               written += num_rows

         return written





