






'''simple docstring'''







from typing import Callable, List, Optional, Union

import PIL
import torch
from transformers import (
    CLIPImageProcessor,
    CLIPSegForImageSegmentation,
    CLIPSegProcessor,
    CLIPTextModel,
    CLIPTokenizer,
)

from diffusers import DiffusionPipeline
from diffusers.configuration_utils import FrozenDict
from diffusers.models import AutoencoderKL, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
from diffusers.utils import deprecate, is_accelerate_available, logging


__lowerCAmelCase       		=      logging.get_logger(__name__)  # pylint: disable=invalid-name





class 	SCREAMING_SNAKE_CASE					(					SCREAMING_SNAKE_CASE_       ):






			def __init__( self      :			str  ,						__SCREAMING_SNAKE_CASE      :			CLIPSegForImageSegmentation  ,						__SCREAMING_SNAKE_CASE      :			CLIPSegProcessor  ,						__SCREAMING_SNAKE_CASE      :			AutoencoderKL  ,						__SCREAMING_SNAKE_CASE      :			CLIPTextModel  ,						__SCREAMING_SNAKE_CASE      :			CLIPTokenizer  ,						__SCREAMING_SNAKE_CASE      :			UNetaDConditionModel  ,						__SCREAMING_SNAKE_CASE      :			Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]  ,						__SCREAMING_SNAKE_CASE      :			StableDiffusionSafetyChecker  ,						__SCREAMING_SNAKE_CASE      :			CLIPImageProcessor  ,						)			->			Union[str, Any]:
							super().__init__()

							if hasattr(scheduler.config  ,						'''steps_offset'''					) and scheduler.config.steps_offset != 1:
											a_		:  int											=      (
											    f'The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`'
											    f' should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure '
											    '''to update the config accordingly as leaving `steps_offset` might led to incorrect results'''
											    ''' in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,'''
											    ''' it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`'''
											    ''' file'''
											)
											deprecate('''steps_offset!=1'''  ,						'''1.0.0'''  ,						__SCREAMING_SNAKE_CASE  ,						standard_warn=__SCREAMING_SNAKE_CASE					)
											a_		:  int											=      dict(scheduler.config					)
											a_		:  List[str]											=      1
											a_		:  List[Any]											=      FrozenDict(__SCREAMING_SNAKE_CASE					)

							if hasattr(scheduler.config  ,						'''skip_prk_steps'''					) and scheduler.config.skip_prk_steps is False:
											a_		:  Union[str, Any]											=      (
											    f'The configuration file of this scheduler: {scheduler} has not set the configuration'
											    ''' `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make'''
											    ''' sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to'''
											    ''' incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face'''
											    ''' Hub, it would be very nice if you could open a Pull request for the'''
											    ''' `scheduler/scheduler_config.json` file'''
											)
											deprecate('''skip_prk_steps not set'''  ,						'''1.0.0'''  ,						__SCREAMING_SNAKE_CASE  ,						standard_warn=__SCREAMING_SNAKE_CASE					)
											a_		:  int											=      dict(scheduler.config					)
											a_		:  List[str]											=      True
											a_		:  Optional[int]											=      FrozenDict(__SCREAMING_SNAKE_CASE					)

							if safety_checker is None:
											logger.warning(
											    f'You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure'
											    ''' that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered'''
											    ''' results in services or applications open to the public. Both the diffusers team and Hugging Face'''
											    ''' strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling'''
											    ''' it only for use-cases that involve analyzing network behavior or auditing its results. For more'''
											    ''' information, please have a look at https://github.com/huggingface/diffusers/pull/254 .'''					)

							self.register_modules(
							    segmentation_model=__SCREAMING_SNAKE_CASE  ,						segmentation_processor=__SCREAMING_SNAKE_CASE  ,						vae=__SCREAMING_SNAKE_CASE  ,						text_encoder=__SCREAMING_SNAKE_CASE  ,						tokenizer=__SCREAMING_SNAKE_CASE  ,						unet=__SCREAMING_SNAKE_CASE  ,						scheduler=__SCREAMING_SNAKE_CASE  ,						safety_checker=__SCREAMING_SNAKE_CASE  ,						feature_extractor=__SCREAMING_SNAKE_CASE  ,						)






			def 			SCREAMING_SNAKE_CASE      ( self      :			List[Any]  ,						__SCREAMING_SNAKE_CASE      :			Optional[Union[str, int]] = "auto"					)			->			List[Any]:
							if slice_size == "auto":
											# half the attention head size is usually a good trade-off between
											# speed and memory
											a_		:  Tuple											=      self.unet.config.attention_head_dim // 2
							self.unet.set_attention_slice(__SCREAMING_SNAKE_CASE					)






			def 			SCREAMING_SNAKE_CASE      ( self      :			List[str]					)			->			Any:
							self.enable_attention_slicing(__SCREAMING_SNAKE_CASE					)






			def 			SCREAMING_SNAKE_CASE      ( self      :			str					)			->			List[Any]:
							if is_accelerate_available():
											from accelerate import cpu_offload
							else:
											raise ImportError('''Please install accelerate via `pip install accelerate`'''					)

							a_		:  List[Any]											=      torch.device('''cuda'''					)

							for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]:
											if cpu_offloaded_model is not None:
															cpu_offload(__SCREAMING_SNAKE_CASE  ,						__SCREAMING_SNAKE_CASE					)






			@property
			# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
			def 			SCREAMING_SNAKE_CASE      ( self      :			Any					)			->			List[str]:
							if self.device != torch.device('''meta'''					) or not hasattr(self.unet  ,						'''_hf_hook'''					):
											return self.device
							for module in self.unet.modules():
											if (
											    hasattr(__SCREAMING_SNAKE_CASE  ,						'''_hf_hook'''					)
											    and hasattr(module._hf_hook  ,						'''execution_device'''					)
											    and module._hf_hook.execution_device is not None
											):
															return torch.device(module._hf_hook.execution_device					)
							return self.device







			@torch.no_grad()
			def __call__( self      :			str  ,						__SCREAMING_SNAKE_CASE      :			Union[str, List[str]]  ,						__SCREAMING_SNAKE_CASE      :			Union[torch.FloatTensor, PIL.Image.Image]  ,						__SCREAMING_SNAKE_CASE      :			str  ,						__SCREAMING_SNAKE_CASE      :			int = 512  ,						__SCREAMING_SNAKE_CASE      :			int = 512  ,						__SCREAMING_SNAKE_CASE      :			int = 50  ,						__SCREAMING_SNAKE_CASE      :			float = 7.5  ,						__SCREAMING_SNAKE_CASE      :			Optional[Union[str, List[str]]] = None  ,						__SCREAMING_SNAKE_CASE      :			Optional[int] = 1  ,						__SCREAMING_SNAKE_CASE      :			float = 0.0  ,						__SCREAMING_SNAKE_CASE      :			Optional[torch.Generator] = None  ,						__SCREAMING_SNAKE_CASE      :			Optional[torch.FloatTensor] = None  ,						__SCREAMING_SNAKE_CASE      :			Optional[str] = "pil"  ,						__SCREAMING_SNAKE_CASE      :			bool = True  ,						__SCREAMING_SNAKE_CASE      :			Optional[Callable[[int, int, torch.FloatTensor], None]] = None  ,						__SCREAMING_SNAKE_CASE      :			int = 1  ,						**__SCREAMING_SNAKE_CASE      :			Dict  ,						)			->			Dict:
							a_		:  Dict											=      self.segmentation_processor(
							    text=[text]  ,						images=[image]  ,						padding='''max_length'''  ,						return_tensors='''pt'''					).to(self.device					)
							a_		:  Optional[Any]											=      self.segmentation_model(**__SCREAMING_SNAKE_CASE					)
							a_		:  Any											=      torch.sigmoid(outputs.logits					).cpu().detach().unsqueeze(-1					).numpy()
							a_		:  Union[str, Any]											=      self.numpy_to_pil(__SCREAMING_SNAKE_CASE					)[0].resize(image.size					)

							# Run inpainting pipeline with the generated mask
							a_		:  str											=      StableDiffusionInpaintPipeline(
							    vae=self.vae  ,						text_encoder=self.text_encoder  ,						tokenizer=self.tokenizer  ,						unet=self.unet  ,						scheduler=self.scheduler  ,						safety_checker=self.safety_checker  ,						feature_extractor=self.feature_extractor  ,						)
							return inpainting_pipeline(
							    prompt=__SCREAMING_SNAKE_CASE  ,						image=__SCREAMING_SNAKE_CASE  ,						mask_image=__SCREAMING_SNAKE_CASE  ,						height=__SCREAMING_SNAKE_CASE  ,						width=__SCREAMING_SNAKE_CASE  ,						num_inference_steps=__SCREAMING_SNAKE_CASE  ,						guidance_scale=__SCREAMING_SNAKE_CASE  ,						negative_prompt=__SCREAMING_SNAKE_CASE  ,						num_images_per_prompt=__SCREAMING_SNAKE_CASE  ,						eta=__SCREAMING_SNAKE_CASE  ,						generator=__SCREAMING_SNAKE_CASE  ,						latents=__SCREAMING_SNAKE_CASE  ,						output_type=__SCREAMING_SNAKE_CASE  ,						return_dict=__SCREAMING_SNAKE_CASE  ,						callback=__SCREAMING_SNAKE_CASE  ,						callback_steps=__SCREAMING_SNAKE_CASE  ,						)












'''simple docstring'''







from unittest.mock import patch

import pyspark

from datasets.packaged_modules.spark.spark import (
    Spark,
    SparkExamplesIterable,
    _generate_iterable_examples,
)

from ..utils import (
    require_dill_gt_0_3_2,
    require_not_windows,
)





def 		_UpperCAmelCase   (							__A							:   List[str]						,		__A							:   List[Any]      ):
				a_		:  Any											=      []
				for part_id in partition_order:
								a_		:  str											=      df.where(f'SPARK_PARTITION_ID() = {part_id}'      ).collect()
								for row_idx, row in enumerate(__A      ):
												expected_row_ids_and_row_dicts.append((f'{part_id}_{row_idx}', row.asDict())      )
				return expected_row_ids_and_row_dicts





@require_not_windows
@require_dill_gt_0_3_2
def 		_UpperCAmelCase   (							):
				a_		:  List[str]											=      pyspark.sql.SparkSession.builder.master('''local[*]'''      ).appName('''pyspark'''      ).getOrCreate()
				a_		:  Union[str, Any]											=      spark.range(1_00      ).repartition(1      )
				a_		:  Any											=      Spark(__A      )
				# The id ints will be converted to Pyarrow int64s, so each row will be 8 bytes. Setting a max_shard_size of 16 means
				# that each partition can hold 2 rows.
				spark_builder._repartition_df_if_needed(max_shard_size=16      )
				# Given that the dataframe has 100 rows and each partition has 2 rows, we expect 50 partitions.
				assert spark_builder.df.rdd.getNumPartitions() == 50





@require_not_windows
@require_dill_gt_0_3_2
def 		_UpperCAmelCase   (							):
				a_		:  List[Any]											=      pyspark.sql.SparkSession.builder.master('''local[*]'''      ).appName('''pyspark'''      ).getOrCreate()
				a_		:  int											=      spark.range(10      ).repartition(2      )
				a_		:  Tuple											=      [1, 0]
				a_		:  List[str]											=      _generate_iterable_examples(__A						,		__A      )  # Reverse the partitions.
				a_		:  int											=      _get_expected_row_ids_and_row_dicts_for_partition_order(__A						,		__A      )

				for i, (row_id, row_dict) in enumerate(generate_fn()      ):
								a_				,			a_		:  List[Any]											=      expected_row_ids_and_row_dicts[i]
								assert row_id == expected_row_id
								assert row_dict == expected_row_dict





@require_not_windows
@require_dill_gt_0_3_2
def 		_UpperCAmelCase   (							):
				a_		:  int											=      pyspark.sql.SparkSession.builder.master('''local[*]'''      ).appName('''pyspark'''      ).getOrCreate()
				a_		:  str											=      spark.range(10      ).repartition(1      )
				a_		:  Tuple											=      SparkExamplesIterable(__A      )
				assert it.n_shards == 1
				for i, (row_id, row_dict) in enumerate(__A      ):
								assert row_id == f'0_{i}'
								assert row_dict == {"id": i}





@require_not_windows
@require_dill_gt_0_3_2
def 		_UpperCAmelCase   (							):
				a_		:  Tuple											=      pyspark.sql.SparkSession.builder.master('''local[*]'''      ).appName('''pyspark'''      ).getOrCreate()
				a_		:  str											=      spark.range(30      ).repartition(3      )
				# Mock the generator so that shuffle reverses the partition indices.
				with patch('''numpy.random.Generator'''      ) as generator_mock:
								a_		:  Union[str, Any]											=      lambda __A      : x.reverse()
								a_		:  Any											=      _get_expected_row_ids_and_row_dicts_for_partition_order(__A						,		[2, 1, 0]      )

								a_		:  str											=      SparkExamplesIterable(__A      ).shuffle_data_sources(__A      )
								assert shuffled_it.n_shards == 3
								for i, (row_id, row_dict) in enumerate(__A      ):
												a_				,			a_		:  Optional[Any]											=      expected_row_ids_and_row_dicts[i]
												assert row_id == expected_row_id
												assert row_dict == expected_row_dict





@require_not_windows
@require_dill_gt_0_3_2
def 		_UpperCAmelCase   (							):
				a_		:  int											=      pyspark.sql.SparkSession.builder.master('''local[*]'''      ).appName('''pyspark'''      ).getOrCreate()
				a_		:  List[str]											=      spark.range(20      ).repartition(4      )

				# Partitions 0 and 2
				a_		:  Dict											=      SparkExamplesIterable(__A      ).shard_data_sources(worker_id=0						,		num_workers=2      )
				assert shard_it_a.n_shards == 2
				a_		:  Optional[Any]											=      _get_expected_row_ids_and_row_dicts_for_partition_order(__A						,		[0, 2]      )
				for i, (row_id, row_dict) in enumerate(__A      ):
								a_				,			a_		:  Tuple											=      expected_row_ids_and_row_dicts_a[i]
								assert row_id == expected_row_id
								assert row_dict == expected_row_dict

				# Partitions 1 and 3
				a_		:  List[Any]											=      SparkExamplesIterable(__A      ).shard_data_sources(worker_id=1						,		num_workers=2      )
				assert shard_it_a.n_shards == 2
				a_		:  Optional[int]											=      _get_expected_row_ids_and_row_dicts_for_partition_order(__A						,		[1, 3]      )
				for i, (row_id, row_dict) in enumerate(__A      ):
								a_				,			a_		:  Any											=      expected_row_ids_and_row_dicts_a[i]
								assert row_id == expected_row_id
								assert row_dict == expected_row_dict





@require_not_windows
@require_dill_gt_0_3_2
def 		_UpperCAmelCase   (							):
				a_		:  Any											=      pyspark.sql.SparkSession.builder.master('''local[*]'''      ).appName('''pyspark'''      ).getOrCreate()
				a_		:  List[Any]											=      spark.range(1_00      ).repartition(1      )
				a_		:  Optional[Any]											=      Spark(__A      )
				# Choose a small max_shard_size for maximum partitioning.
				spark_builder._repartition_df_if_needed(max_shard_size=1      )
				# The new number of partitions should not be greater than the number of rows.
				assert spark_builder.df.rdd.getNumPartitions() == 1_00




