


'''simple docstring'''







import random
import unittest

import numpy as np
import torch
from PIL import Image
from torch import nn
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModelWithProjection,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import KandinskyVaaPriorEmbaEmbPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import floats_tensor, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()
class  lowercase_					(   a__  ,						unittest.TestCase       ):
    __UpperCAmelCase             =     KandinskyVaaPriorEmbaEmbPipeline
    __UpperCAmelCase             =     ['prompt', 'image']
    __UpperCAmelCase             =     ['prompt', 'image']
    __UpperCAmelCase             =     [
        'num_images_per_prompt',
        'strength',
        'generator',
        'num_inference_steps',
        'latents',
        'negative_prompt',
        'guidance_scale',
        'output_type',
        'return_dict',
    ]
    __UpperCAmelCase             =     False


    @property
    def        __a							(					self   ):
          return 32


    @property
    def        __a							(					self   ):
          return 32


    @property
    def        __a							(					self   ):
          return self.time_input_dim


    @property
    def        __a							(					self   ):
          return self.time_input_dim * 4


    @property
    def        __a							(					self   ):
          return 1_00


    @property
    def        __a							(					self   ):
          UpperCamelCase__  =    CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"   )
          return tokenizer


    @property
    def        __a							(					self   ):
          torch.manual_seed(0   )
          UpperCamelCase__  =    CLIPTextConfig(
              bos_token_id=0  , eos_token_id=2  , hidden_size=self.text_embedder_hidden_size  , projection_dim=self.text_embedder_hidden_size  , intermediate_size=37  , layer_norm_eps=1e-05  , num_attention_heads=4  , num_hidden_layers=5  , pad_token_id=1  , vocab_size=10_00  , )
          return CLIPTextModelWithProjection(a   )


    @property
    def        __a							(					self   ):
          torch.manual_seed(0   )

          UpperCamelCase__  =    {
              "num_attention_heads": 2,
              "attention_head_dim": 12,
              "embedding_dim": self.text_embedder_hidden_size,
              "num_layers": 1,
          }

          UpperCamelCase__  =    PriorTransformer(**a   )
          # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
          UpperCamelCase__  =    nn.Parameter(torch.ones(model.clip_std.shape   )   )
          return model


    @property
    def        __a							(					self   ):
          torch.manual_seed(0   )
          UpperCamelCase__  =    CLIPVisionConfig(
              hidden_size=self.text_embedder_hidden_size  , image_size=2_24  , projection_dim=self.text_embedder_hidden_size  , intermediate_size=37  , num_attention_heads=4  , num_channels=3  , num_hidden_layers=5  , patch_size=14  , )

          UpperCamelCase__  =    CLIPVisionModelWithProjection(a   )
          return model


    @property
    def        __a							(					self   ):
          UpperCamelCase__  =    CLIPImageProcessor(
              crop_size=2_24  , do_center_crop=a  , do_normalize=a  , do_resize=a  , image_mean=[0.4814_5466, 0.457_8275, 0.4082_1073]  , image_std=[0.2686_2954, 0.2613_0258, 0.2757_7711]  , resample=3  , size=2_24  , )

          return image_processor


    def        __a							(					self   ):
          UpperCamelCase__  =    self.dummy_prior
          UpperCamelCase__  =    self.dummy_image_encoder
          UpperCamelCase__  =    self.dummy_text_encoder
          UpperCamelCase__  =    self.dummy_tokenizer
          UpperCamelCase__  =    self.dummy_image_processor

          UpperCamelCase__  =    UnCLIPScheduler(
              variance_type="fixed_small_log"  , prediction_type="sample"  , num_train_timesteps=10_00  , clip_sample=a  , clip_sample_range=10.0  , )

          UpperCamelCase__  =    {
              "prior": prior,
              "image_encoder": image_encoder,
              "text_encoder": text_encoder,
              "tokenizer": tokenizer,
              "scheduler": scheduler,
              "image_processor": image_processor,
          }

          return components


    def        __a							(					self  , a  , a=0   ):
          if str(a   ).startswith("mps"   ):
                UpperCamelCase__  =    torch.manual_seed(a   )
          else:
                UpperCamelCase__  =    torch.Generator(device=a   ).manual_seed(a   )

          UpperCamelCase__  =    floats_tensor((1, 3, 64, 64)  , rng=random.Random(a   )   ).to(a   )
          UpperCamelCase__  =    image.cpu().permute(0  , 2  , 3  , 1   )[0]
          UpperCamelCase__  =    Image.fromarray(np.uinta(a   )   ).convert("RGB"   ).resize((2_56, 2_56)   )

          UpperCamelCase__  =    {
              "prompt": "horse",
              "image": init_image,
              "strength": 0.5,
              "generator": generator,
              "guidance_scale": 4.0,
              "num_inference_steps": 2,
              "output_type": "np",
          }
          return inputs


    def        __a							(					self   ):
          UpperCamelCase__  =    "cpu"

          UpperCamelCase__  =    self.get_dummy_components()

          UpperCamelCase__  =    self.pipeline_class(**a   )
          UpperCamelCase__  =    pipe.to(a   )

          pipe.set_progress_bar_config(disable=a   )

          UpperCamelCase__  =    pipe(**self.get_dummy_inputs(a   )   )
          UpperCamelCase__  =    output.image_embeds

          UpperCamelCase__  =    pipe(
              **self.get_dummy_inputs(a   )  , return_dict=a  , )[0]

          UpperCamelCase__  =    image[0, -10:]
          UpperCamelCase__  =    image_from_tuple[0, -10:]

          assert image.shape == (1, 32)

          UpperCamelCase__  =    np.array(
              [
                  0.107_1284,
                  1.333_0271,
                  0.6126_0223,
                  -0.669_1065,
                  -0.384_6852,
                  -1.030_3661,
                  0.2271_6111,
                  0.0334_8901,
                  0.3004_0675,
                  -0.2480_5029,
              ]   )

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


    @skip_mps
    def        __a							(					self   ):
          UpperCamelCase__  =    torch_device == "cpu"
          UpperCamelCase__  =    True
          UpperCamelCase__  =    False

          self._test_inference_batch_single_identical(
              test_max_difference=a  , relax_max_difference=a  , test_mean_pixel_difference=a  , )


    @skip_mps
    def        __a							(					self   ):
          UpperCamelCase__  =    torch_device == "cpu"
          UpperCamelCase__  =    False

          self._test_attention_slicing_forward_pass(
              test_max_difference=a  , test_mean_pixel_difference=a  , )









'''simple docstring'''







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


a__  : Optional[int]				=	datasets.utils.logging.get_logger(__name__)
@dataclass
class  lowercase_					(   datasets.BuilderConfig       ):
    __UpperCAmelCase             =     None
    __UpperCAmelCase             =     None
    __UpperCAmelCase             =     None
    __UpperCAmelCase             =     True
    __UpperCAmelCase             =     None
    __UpperCAmelCase             =     None
    __UpperCAmelCase             =     None
    __UpperCAmelCase             =     10000
    __UpperCAmelCase             =     None


    def        __a							(					self   ):
          if self.sql is None:
                raise ValueError("sql must be specified"   )
          if self.con is None:
                raise ValueError("con must be specified"   )


    def        __a							(					self  , a  , a = None  , ):
          UpperCamelCase__  =    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
          UpperCamelCase__  =    config_kwargs["sql"]
          if not isinstance(a  , a   ):
                if datasets.config.SQLALCHEMY_AVAILABLE and "sqlalchemy" in sys.modules:
                      import sqlalchemy

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

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


    @property
    def        __a							(					self   ):
          UpperCamelCase__  =    {
              "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  lowercase_					(   datasets.ArrowBasedBuilder       ):
    __UpperCAmelCase             =     SqlConfig


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


    def        __a							(					self  , a   ):
          return [datasets.SplitGenerator(name=datasets.Split.TRAIN  , gen_kwargs={}   )]


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


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





