




import sys
from dataclasses import dataclass
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union

import pandas as pd
import pyarrow as pa

import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast


if TYPE_CHECKING:
   import sqlitea

   import sqlalchemy


lowerCamelCase__				:     Dict			       =							datasets.utils.logging.get_logger(__name__)





@dataclass
class  lowerCamelCase_							(   datasets.BuilderConfig      ):


 '''simple docstring'''







 lowercase_       					=					None
 lowercase_       					=					None
 lowercase_       					=					None
 lowercase_       					=					True
 lowercase_       					=					None
 lowercase_       					=					None
 lowercase_       					=					None
 lowercase_       					=					10_000
 lowercase_       					=					None



 def    lowerCAmelCase_						(							self						:	List[str]		):



       if self.sql is None:
             raise ValueError('sql must be specified'		)
       if self.con is None:
             raise ValueError('con must be specified'		)



 def    lowerCAmelCase_						(							self						:	Optional[Any]       ,       _lowerCAmelCase						:	Union[str, Any]       ,       _lowerCAmelCase						:	Union[str, Any] = None       ,       ):
       SCREAMING_SNAKE_CASE_					=    config_kwargs.copy()
       # We need to stringify the Selectable object to make its hash deterministic

       # The process of stringifying is explained here: http://docs.sqlalchemy.org/en/latest/faq/sqlexpressions.html
       SCREAMING_SNAKE_CASE_					=    config_kwargs['sql']
       if not isinstance(lowerCamelCase__       ,       lowerCamelCase__		):
             if datasets.config.SQLALCHEMY_AVAILABLE and "sqlalchemy" in sys.modules:
                   import sqlalchemy

                   if isinstance(lowerCamelCase__       ,       sqlalchemy.sql.Selectable		):
                         SCREAMING_SNAKE_CASE_					=    sqlalchemy.create_engine(config_kwargs['con'].split('://'		)[0] + '://'		)
                         SCREAMING_SNAKE_CASE_					=    str(sql.compile(dialect=engine.dialect		)		)
                         SCREAMING_SNAKE_CASE_					=    sql_str
                   else:
                         raise TypeError(
                             F"Supported types for \'sql\' are string and sqlalchemy.sql.Selectable but got {type(lowerCamelCase__		)}: {sql}"		)
             else:
                   raise TypeError(
                       F"Supported types for \'sql\' are string and sqlalchemy.sql.Selectable but got {type(lowerCamelCase__		)}: {sql}"		)
       SCREAMING_SNAKE_CASE_					=    config_kwargs['con']
       if not isinstance(lowerCamelCase__       ,       lowerCamelCase__		):
             SCREAMING_SNAKE_CASE_					=    id(lowerCamelCase__		)
             logger.info(
                 F"SQL connection \'con\' of type {type(lowerCamelCase__		)} couldn\'t be hashed properly. To enable hashing, specify \'con\' as URI string instead."		)

       return super().create_config_id(lowerCamelCase__       ,       custom_features=lowerCamelCase__		)




 @property
 def    lowerCAmelCase_						(							self						:	List[str]		):
       SCREAMING_SNAKE_CASE_					=    {
           'index_col': self.index_col,
           'columns': self.columns,
           'params': self.params,
           'coerce_float': self.coerce_float,
           'parse_dates': self.parse_dates,
       }
       return pd_read_sql_kwargs





class  lowerCamelCase_							(   datasets.ArrowBasedBuilder      ):


 '''simple docstring'''







 lowercase_       					=					SqlConfig



 def    lowerCAmelCase_						(							self						:	Tuple		):
       return datasets.DatasetInfo(features=self.config.features		)



 def    lowerCAmelCase_						(							self						:	Union[str, Any]       ,       _lowerCAmelCase						:	List[Any]		):
       return [datasets.SplitGenerator(name=datasets.Split.TRAIN       ,       gen_kwargs={}		)]



 def    lowerCAmelCase_						(							self						:	Optional[int]       ,       _lowerCAmelCase						:	List[Any]		):



       if self.config.features is not None:
             SCREAMING_SNAKE_CASE_					=    self.config.features.arrow_schema
             if all(not require_storage_cast(lowerCamelCase__		) for feature in self.config.features.values()		):
                   # cheaper cast
                   SCREAMING_SNAKE_CASE_					=    pa.Table.from_arrays([pa_table[field.name] for field in schema]       ,       schema=lowerCamelCase__		)
             else:
                   # more expensive cast; allows str <-> int/float or str to Audio for example
                   SCREAMING_SNAKE_CASE_					=    table_cast(lowerCamelCase__       ,       lowerCamelCase__		)
       return pa_table




 def    lowerCAmelCase_						(							self						:	List[str]		):
       SCREAMING_SNAKE_CASE_					=    self.config.chunksize
       SCREAMING_SNAKE_CASE_					=    pd.read_sql(
           self.config.sql       ,       self.config.con       ,       chunksize=lowerCamelCase__       ,       **self.config.pd_read_sql_kwargs		)
       SCREAMING_SNAKE_CASE_					=    [sql_reader] if chunksize is None else sql_reader
       for chunk_idx, df in enumerate(lowerCamelCase__		):
             SCREAMING_SNAKE_CASE_					=    pa.Table.from_pandas(lowerCamelCase__		)
             yield chunk_idx, self._cast_table(lowerCamelCase__		)








import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionDualGuidedPipeline
from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device


lowerCamelCase__				:     int			       =							False





@nightly
@require_torch_gpu
class  lowerCamelCase_							(   unittest.TestCase      ):


 '''simple docstring'''







 def    lowerCAmelCase_						(							self						:	Optional[Any]		):
       # clean up the VRAM after each test
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()



 def    lowerCAmelCase_						(							self						:	Optional[int]		):
       SCREAMING_SNAKE_CASE_					=    VersatileDiffusionDualGuidedPipeline.from_pretrained('shi-labs/versatile-diffusion'		)
       # remove text_unet
       pipe.remove_unused_weights()
       pipe.to(_lowerCAmelCase		)
       pipe.set_progress_bar_config(disable=_lowerCAmelCase		)

       SCREAMING_SNAKE_CASE_					=    load_image(
           'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg'		)

       SCREAMING_SNAKE_CASE_					=    torch.manual_seed(0		)
       SCREAMING_SNAKE_CASE_					=    pipe(
           prompt='first prompt'       ,       image=_lowerCAmelCase       ,       text_to_image_strength=0.75       ,       generator=_lowerCAmelCase       ,       guidance_scale=7.5       ,       num_inference_steps=2       ,       output_type='numpy'       ,       ).images

       with tempfile.TemporaryDirectory() as tmpdirname:
             pipe.save_pretrained(_lowerCAmelCase		)
             SCREAMING_SNAKE_CASE_					=    VersatileDiffusionDualGuidedPipeline.from_pretrained(_lowerCAmelCase		)

       pipe.to(_lowerCAmelCase		)
       pipe.set_progress_bar_config(disable=_lowerCAmelCase		)

       SCREAMING_SNAKE_CASE_					=    generator.manual_seed(0		)
       SCREAMING_SNAKE_CASE_					=    pipe(
           prompt='first prompt'       ,       image=_lowerCAmelCase       ,       text_to_image_strength=0.75       ,       generator=_lowerCAmelCase       ,       guidance_scale=7.5       ,       num_inference_steps=2       ,       output_type='numpy'       ,       ).images

       assert np.abs(image - new_image		).sum() < 1E-5, "Models don't have the same forward pass"




 def    lowerCAmelCase_						(							self						:	Any		):
       SCREAMING_SNAKE_CASE_					=    VersatileDiffusionDualGuidedPipeline.from_pretrained('shi-labs/versatile-diffusion'		)
       pipe.remove_unused_weights()
       pipe.to(_lowerCAmelCase		)
       pipe.set_progress_bar_config(disable=_lowerCAmelCase		)

       SCREAMING_SNAKE_CASE_					=    'cyberpunk 2077'
       SCREAMING_SNAKE_CASE_					=    load_image(
           'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg'		)
       SCREAMING_SNAKE_CASE_					=    torch.manual_seed(0		)
       SCREAMING_SNAKE_CASE_					=    pipe(
           prompt=_lowerCAmelCase       ,       image=_lowerCAmelCase       ,       text_to_image_strength=0.75       ,       generator=_lowerCAmelCase       ,       guidance_scale=7.5       ,       num_inference_steps=50       ,       output_type='numpy'       ,       ).images

       SCREAMING_SNAKE_CASE_					=    image[0, 253:256, 253:256, -1]

       assert image.shape == (1, 512, 512, 3)
       SCREAMING_SNAKE_CASE_					=    np.array([0.0787, 0.0849, 0.0826, 0.0812, 0.0807, 0.0795, 0.0818, 0.0798, 0.0779]		)

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