




from __future__ import annotations






def  snake_case (							A      )							->							list[int]:




	'''simple docstring'''


	lowerCamelCase_							:		Any							       =							[0] * len(A      )
	for i in range(1						,       len(A      )      ):
		lowerCamelCase_							:		Dict							       =							duration_times[i - 1] + waiting_times[i - 1]
	return waiting_times






def  snake_case (							A						,       A      )							->							list[int]:




	'''simple docstring'''


	return [
	    duration_time + waiting_times[i]
	    for i, duration_time in enumerate(A      )
	]






def  snake_case (							A      )							->							float:




	'''simple docstring'''


	return sum(A      ) / len(A      )






def  snake_case (							A      )							->							float:




	'''simple docstring'''


	return sum(A      ) / len(A      )


if __name__ == "__main__":
							# process id's
							UpperCamelCase__		=						[1, 2, 3]

							# ensure that we actually have processes
							if len(processes) == 0:
														print('Zero amount of processes')
														raise SystemExit(0)

							# duration time of all processes
							UpperCamelCase__		=						[1_9, 8, 9]

							# ensure we can match each id to a duration time
							if len(duration_times) != len(processes):
														print('Unable to match all id\'s with their duration time')
														raise SystemExit(0)

							# get the waiting times and the turnaround times
							UpperCamelCase__		=						calculate_waiting_times(duration_times)
							UpperCamelCase__		=						calculate_turnaround_times(duration_times, waiting_times)

							# get the average times
							UpperCamelCase__		=						calculate_average_waiting_time(waiting_times)
							UpperCamelCase__		=						calculate_average_turnaround_time(turnaround_times)

							# print all the results
							print('Process ID\tDuration Time\tWaiting Time\tTurnaround Time')
							for i, process in enumerate(processes):
														print(
														    F'{process}\t\t{duration_times[i]}\t\t{waiting_times[i]}\t\t'
														    F'{turnaround_times[i]}'
														)
							print(F'Average waiting time = {average_waiting_time}')
							print(F'Average turn around time = {average_turnaround_time}')






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     __SCREAMING_SNAKE_CASE							(		lowerCamelCase       ,					unittest.TestCase  ):
					_lowerCamelCase		  =			KandinskyVaaPriorEmbaEmbPipeline
					_lowerCamelCase		  =			["""prompt""", """image"""]
					_lowerCamelCase		  =			["""prompt""", """image"""]
					_lowerCamelCase		  =			[
					    """num_images_per_prompt""",
					    """strength""",
					    """generator""",
					    """num_inference_steps""",
					    """latents""",
					    """negative_prompt""",
					    """guidance_scale""",
					    """output_type""",
					    """return_dict""",
					]
					_lowerCamelCase		  =			False

					@property
					def      lowercase_							(    self ):







						'''simple docstring'''




						return 32

					@property
					def      lowercase_							(    self ):







						'''simple docstring'''




						return 32

					@property
					def      lowercase_							(    self ):







						'''simple docstring'''




						return self.time_input_dim

					@property
					def      lowercase_							(    self ):







						'''simple docstring'''




						return self.time_input_dim * 4

					@property
					def      lowercase_							(    self ):







						'''simple docstring'''




						return 100

					@property
					def      lowercase_							(    self ):







						'''simple docstring'''




						lowerCamelCase_							:		Dict							       =							CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' )
						return tokenizer

					@property
					def      lowercase_							(    self ):







						'''simple docstring'''




						torch.manual_seed(0 )
						lowerCamelCase_							:		Dict							       =							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=1_000			,	)
						return CLIPTextModelWithProjection(__lowercase )

					@property
					def      lowercase_							(    self ):







						'''simple docstring'''




						torch.manual_seed(0 )

						lowerCamelCase_							:		int							       =							{
						    'num_attention_heads': 2,
						    'attention_head_dim': 12,
						    'embedding_dim': self.text_embedder_hidden_size,
						    'num_layers': 1,
						}

						lowerCamelCase_							:		str							       =							PriorTransformer(**__lowercase )
						# 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
						lowerCamelCase_							:		Dict							       =							nn.Parameter(torch.ones(model.clip_std.shape ) )
						return model

					@property
					def      lowercase_							(    self ):







						'''simple docstring'''




						torch.manual_seed(0 )
						lowerCamelCase_							:		str							       =							CLIPVisionConfig(
						    hidden_size=self.text_embedder_hidden_size			,	image_size=224			,	projection_dim=self.text_embedder_hidden_size			,	intermediate_size=37			,	num_attention_heads=4			,	num_channels=3			,	num_hidden_layers=5			,	patch_size=14			,	)

						lowerCamelCase_							:		List[str]							       =							CLIPVisionModelWithProjection(__lowercase )
						return model

					@property
					def      lowercase_							(    self ):







						'''simple docstring'''




						lowerCamelCase_							:		int							       =							CLIPImageProcessor(
						    crop_size=224			,	do_center_crop=__lowercase			,	do_normalize=__lowercase			,	do_resize=__lowercase			,	image_mean=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73]			,	image_std=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11]			,	resample=3			,	size=224			,	)

						return image_processor

					def      lowercase_							(    self ):







						'''simple docstring'''




						lowerCamelCase_							:		List[Any]							       =							self.dummy_prior
						lowerCamelCase_							:		str							       =							self.dummy_image_encoder
						lowerCamelCase_							:		Tuple							       =							self.dummy_text_encoder
						lowerCamelCase_							:		str							       =							self.dummy_tokenizer
						lowerCamelCase_							:		int							       =							self.dummy_image_processor

						lowerCamelCase_							:		Dict							       =							UnCLIPScheduler(
						    variance_type='fixed_small_log'			,	prediction_type='sample'			,	num_train_timesteps=1_000			,	clip_sample=__lowercase			,	clip_sample_range=10.0			,	)

						lowerCamelCase_							:		Dict							       =							{
						    'prior': prior,
						    'image_encoder': image_encoder,
						    'text_encoder': text_encoder,
						    'tokenizer': tokenizer,
						    'scheduler': scheduler,
						    'image_processor': image_processor,
						}

						return components

					def      lowercase_							(    self			,	__lowercase			,	__lowercase=0 ):







						'''simple docstring'''




						if str(__lowercase ).startswith('mps' ):
							lowerCamelCase_							:		Union[str, Any]							       =							torch.manual_seed(__lowercase )
						else:
							lowerCamelCase_							:		Optional[Any]							       =							torch.Generator(device=__lowercase ).manual_seed(__lowercase )

						lowerCamelCase_							:		Optional[int]							       =							floats_tensor((1, 3, 64, 64)			,	rng=random.Random(__lowercase ) ).to(__lowercase )
						lowerCamelCase_							:		Any							       =							image.cpu().permute(0			,	2			,	3			,	1 )[0]
						lowerCamelCase_							:		List[Any]							       =							Image.fromarray(np.uinta(__lowercase ) ).convert('RGB' ).resize((256, 256) )

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

					def      lowercase_							(    self ):







						'''simple docstring'''




						lowerCamelCase_							:		str							       =							'cpu'

						lowerCamelCase_							:		Union[str, Any]							       =							self.get_dummy_components()

						lowerCamelCase_							:		str							       =							self.pipeline_class(**__lowercase )
						lowerCamelCase_							:		Optional[Any]							       =							pipe.to(__lowercase )

						pipe.set_progress_bar_config(disable=__lowercase )

						lowerCamelCase_							:		List[str]							       =							pipe(**self.get_dummy_inputs(__lowercase ) )
						lowerCamelCase_							:		Union[str, Any]							       =							output.image_embeds

						lowerCamelCase_							:		List[str]							       =							pipe(
						    **self.get_dummy_inputs(__lowercase )			,	return_dict=__lowercase			,	)[0]

						lowerCamelCase_							:		List[Any]							       =							image[0, -10:]
						lowerCamelCase_							:		List[Any]							       =							image_from_tuple[0, -10:]

						assert image.shape == (1, 32)

						lowerCamelCase_							:		Any							       =							np.array(
						    [
						        0.1_07_12_84,
						        1.3_33_02_71,
						        0.61_26_02_23,
						        -0.6_69_10_65,
						        -0.3_84_68_52,
						        -1.0_30_36_61,
						        0.22_71_61_11,
						        0.03_34_89_01,
						        0.30_04_06_75,
						        -0.24_80_50_29,
						    ] )

						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      lowercase_							(    self ):







						'''simple docstring'''




						lowerCamelCase_							:		int							       =							torch_device == 'cpu'
						lowerCamelCase_							:		Union[str, Any]							       =							True
						lowerCamelCase_							:		str							       =							False

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





					@skip_mps
					def      lowercase_							(    self ):







						'''simple docstring'''




						lowerCamelCase_							:		Optional[Any]							       =							torch_device == 'cpu'
						lowerCamelCase_							:		Optional[Any]							       =							False

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