


from abc import ABC, abstractmethod
from typing import List, Optional




class       lowercase_					(lowercase__   ):





				def __init__(				self)  -> List[str]:
											# test for the above condition
											self.test()





				def 						__UpperCamelCase    (				self)  -> List[str]:
											a__      =0
											a__      =False
											while not completed:
																		if counter == 1:
																									self.reset()
																		a__      =self.advance()
																		if not self.does_advance(lowercase_):
																									raise Exception(
																									    'Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.')

																		a__    ,     a__    ,     a__      =self.update(lowercase_)
																		counter += 1

																		if counter > 10000:
																									raise Exception('update() does not fulfill the constraint.')

											if self.remaining() != 0:
																		raise Exception('Custom Constraint is not defined correctly.')





				@abstractmethod
				def 						__UpperCamelCase    (				self)  -> Optional[int]:
											raise NotImplementedError(
											    F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""")





				@abstractmethod
				def 						__UpperCamelCase    (				self       ,  lowercase_)  -> Dict:
											raise NotImplementedError(
											    F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""")





				@abstractmethod
				def 						__UpperCamelCase    (				self       ,  lowercase_)  -> Optional[Any]:
											raise NotImplementedError(
											    F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""")





				@abstractmethod
				def 						__UpperCamelCase    (				self)  -> List[str]:
											raise NotImplementedError(
											    F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""")





				@abstractmethod
				def 						__UpperCamelCase    (				self)  -> Optional[Any]:
											raise NotImplementedError(
											    F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""")





				@abstractmethod
				def 						__UpperCamelCase    (				self       ,  lowercase_=False)  -> Optional[Any]:
											raise NotImplementedError(
											    F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""")







class       lowercase_					(lowercase__   ):





				def __init__(				self       ,  lowercase_)  -> Union[str, Any]:
											super(lowercase_       ,  self).__init__()

											if not isinstance(lowercase_       ,  lowercase_) or len(lowercase_) == 0:
																		raise ValueError(F"""`token_ids` has to be a non-empty list, but is {token_ids}.""")
											if any((not isinstance(lowercase_       ,  lowercase_) or token_id < 0) for token_id in token_ids):
																		raise ValueError(F"""Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.""")

											a__      =token_ids

											a__      =len(self.token_ids)
											a__      =-1  # the index of the currently fulfilled step
											a__      =False





				def 						__UpperCamelCase    (				self)  -> Dict:
											if self.completed:
																		return None
											return self.token_ids[self.fulfilled_idx + 1]





				def 						__UpperCamelCase    (				self       ,  lowercase_)  -> int:
											if not isinstance(lowercase_       ,  lowercase_):
																		raise ValueError(F"""`token_id` has to be an `int`, but is {token_id} of type {type(lowercase_)}""")

											if self.completed:
																		return False

											return token_id == self.token_ids[self.fulfilled_idx + 1]





				def 						__UpperCamelCase    (				self       ,  lowercase_)  -> Tuple:
											if not isinstance(lowercase_       ,  lowercase_):
																		raise ValueError(F"""`token_id` has to be an `int`, but is {token_id} of type {type(lowercase_)}""")

											a__      =False
											a__      =False
											a__      =False

											if self.does_advance(lowercase_):
																		self.fulfilled_idx += 1
																		a__      =True
																		if self.fulfilled_idx == (self.seqlen - 1):
																									a__      =True
																		a__      =completed
											else:
																		# failed to make progress.
																		a__      =True
																		self.reset()
											return stepped, completed, reset





				def 						__UpperCamelCase    (				self)  -> Optional[Any]:
											a__      =False
											a__      =0





				def 						__UpperCamelCase    (				self)  -> int:
											return self.seqlen - (self.fulfilled_idx + 1)





				def 						__UpperCamelCase    (				self       ,  lowercase_=False)  -> List[str]:
											a__      =PhrasalConstraint(self.token_ids)

											if stateful:
																		a__      =self.seqlen
																		a__      =self.fulfilled_idx
																		a__      =self.completed

											return new_constraint







class       lowercase_					:





				def __init__(				self       ,  lowercase_       ,  lowercase_=True)  -> Optional[Any]:
											a__      =max([len(lowercase_) for one in nested_token_ids])

											a__      ={}
											for token_ids in nested_token_ids:
																		a__      =root
																		for tidx, token_id in enumerate(lowercase_):
																									if token_id not in level:
																																a__      ={}

																									a__      =level[token_id]

											if no_subsets and self.has_subsets(lowercase_       ,  lowercase_):
																		raise ValueError(
																		    'Each list in `nested_token_ids` can\'t be a complete subset of another list, but is'
																		    F""" {nested_token_ids}.""")

											a__      =root





				def 						__UpperCamelCase    (				self       ,  lowercase_)  -> Union[str, Any]:
											a__      =self.trie

											for current_token in current_seq:
																		a__      =start[current_token]

											a__      =list(start.keys())

											return next_tokens





				def 						__UpperCamelCase    (				self       ,  lowercase_)  -> List[str]:
											a__      =self.next_tokens(lowercase_)

											return len(lowercase_) == 0





				def 						__UpperCamelCase    (				self       ,  lowercase_)  -> str:
											a__      =list(root.values())
											if len(lowercase_) == 0:
																		return 1
											else:
																		return sum([self.count_leaves(lowercase_) for nn in next_nodes])





				def 						__UpperCamelCase    (				self       ,  lowercase_       ,  lowercase_)  -> Any:
											a__      =self.count_leaves(lowercase_)
											return len(lowercase_) != leaf_count







class       lowercase_					(lowercase__   ):





				def __init__(				self       ,  lowercase_)  -> Any:
											super(lowercase_       ,  self).__init__()

											if not isinstance(lowercase_       ,  lowercase_) or len(lowercase_) == 0:
																		raise ValueError(F"""`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.""")
											if any(not isinstance(lowercase_       ,  lowercase_) for token_ids in nested_token_ids):
																		raise ValueError(F"""`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.""")
											if any(
											    any((not isinstance(lowercase_       ,  lowercase_) or token_id < 0) for token_id in token_ids)
											    for token_ids in nested_token_ids):
																		raise ValueError(
																		    F"""Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}.""")

											a__      =DisjunctiveTrie(lowercase_)
											a__      =nested_token_ids

											a__      =self.trie.max_height
											a__      =[]
											a__      =False





				def 						__UpperCamelCase    (				self)  -> Tuple:
											a__      =self.trie.next_tokens(self.current_seq)

											if len(lowercase_) == 0:
																		return None
											else:
																		return token_list





				def 						__UpperCamelCase    (				self       ,  lowercase_)  -> Optional[int]:
											if not isinstance(lowercase_       ,  lowercase_):
																		raise ValueError(F"""`token_id` is supposed to be type `int`, but is {token_id} of type {type(lowercase_)}""")

											a__      =self.trie.next_tokens(self.current_seq)

											return token_id in next_tokens





				def 						__UpperCamelCase    (				self       ,  lowercase_)  -> Tuple:
											if not isinstance(lowercase_       ,  lowercase_):
																		raise ValueError(F"""`token_id` is supposed to be type `int`, but is {token_id} of type {type(lowercase_)}""")

											a__      =False
											a__      =False
											a__      =False

											if self.does_advance(lowercase_):
																		self.current_seq.append(lowercase_)
																		a__      =True
											else:
																		a__      =True
																		self.reset()

											a__      =self.trie.reached_leaf(self.current_seq)
											a__      =completed

											return stepped, completed, reset





				def 						__UpperCamelCase    (				self)  -> int:
											a__      =False
											a__      =[]





				def 						__UpperCamelCase    (				self)  -> Optional[Any]:
											if self.completed:
																		# since this can be completed without reaching max height
																		return 0
											else:
																		return self.seqlen - len(self.current_seq)





				def 						__UpperCamelCase    (				self       ,  lowercase_=False)  -> Dict:
											a__      =DisjunctiveConstraint(self.token_ids)

											if stateful:
																		a__      =self.seqlen
																		a__      =self.current_seq
																		a__      =self.completed

											return new_constraint







class       lowercase_					:





				def __init__(				self       ,  lowercase_)  -> int:
											a__      =constraints

											# max # of steps required to fulfill a given constraint
											a__      =max([c.seqlen for c in constraints])
											a__      =len(lowercase_)
											a__      =False

											self.init_state()





				def 						__UpperCamelCase    (				self)  -> Optional[Any]:
											a__      =[]
											a__      =None
											a__      =[constraint.copy(stateful=lowercase_) for constraint in self.constraints]





				def 						__UpperCamelCase    (				self)  -> Union[str, Any]:
											a__      =0
											if self.inprogress_constraint:
																		# extra points for having a constraint mid-fulfilled
																		add += self.max_seqlen - self.inprogress_constraint.remaining()

											return (len(self.complete_constraints) * self.max_seqlen) + add





				def 						__UpperCamelCase    (				self)  -> Union[str, Any]:
											a__      =[]
											if self.inprogress_constraint is None:
																		for constraint in self.pending_constraints:  # "pending" == "unfulfilled yet"
																									a__      =constraint.advance()
																									if isinstance(lowercase_       ,  lowercase_):
																																token_list.append(lowercase_)
																									elif isinstance(lowercase_       ,  lowercase_):
																																token_list.extend(lowercase_)
											else:
																		a__      =self.inprogress_constraint.advance()
																		if isinstance(lowercase_       ,  lowercase_):
																									token_list.append(lowercase_)
																		elif isinstance(lowercase_       ,  lowercase_):
																									token_list.extend(lowercase_)

											if len(lowercase_) == 0:
																		return None
											else:
																		return token_list





				def 						__UpperCamelCase    (				self       ,  lowercase_)  -> Tuple:
											self.init_state()

											if token_ids is not None:
																		for token in token_ids:
																									# completes or steps **one** constraint
																									a__    ,     a__      =self.add(lowercase_)

																									# the entire list of constraints are fulfilled
																									if self.completed:
																																break





				def 						__UpperCamelCase    (				self       ,  lowercase_)  -> Optional[Any]:
											if not isinstance(lowercase_       ,  lowercase_):
																		raise ValueError(F"""`token_id` should be an `int`, but is `{token_id}`.""")

											a__    ,     a__      =False, False

											if self.completed:
																		a__      =True
																		a__      =False
																		return complete, stepped

											if self.inprogress_constraint is not None:
																		# In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current
																		# job, simply update the state

																		a__    ,     a__    ,     a__      =self.inprogress_constraint.update(lowercase_)
																		if reset:
																									# 1. If the next token breaks the progress, then we must restart.
																									#     e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books".

																									#     But that doesn't mean we self.init_state(), since we only reset the state for this particular
																									#     constraint, not the full list of constraints.

																									self.pending_constraints.append(self.inprogress_constraint.copy(stateful=lowercase_))
																									a__      =None

																		if complete:
																									# 2. If the next token completes the constraint, move it to completed list, set
																									#     inprogress to None. If there are no pending constraints either, then this full list of constraints
																									#     is complete.

																									self.complete_constraints.append(self.inprogress_constraint)
																									a__      =None

																									if len(self.pending_constraints) == 0:
																																# we're done!
																																a__      =True

											else:
																		# Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list
																		# of constraints?

																		for cidx, pending_constraint in enumerate(self.pending_constraints):
																									if pending_constraint.does_advance(lowercase_):
																																a__    ,     a__    ,     a__      =pending_constraint.update(lowercase_)

																																if not stepped:
																																							raise Exception(
																																							    '`constraint.update(token_id)` is not yielding incremental progress, '
																																							    'even though `constraint.does_advance(token_id)` is true.')

																																if complete:
																																							self.complete_constraints.append(lowercase_)
																																							a__      =None

																																if not complete and stepped:
																																							a__      =pending_constraint

																																if complete or stepped:
																																							# If we made any progress at all, then it's at least not a "pending constraint".

																																							a__      =(
																																							    self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :]
																																							)

																																							if len(self.pending_constraints) == 0 and self.inprogress_constraint is None:
																																														# If there's no longer any pending after this and no inprogress either, then we must be
																																														# complete.

																																														a__      =True

																																							break  # prevent accidentally stepping through multiple constraints with just one token.

											return complete, stepped





				def 						__UpperCamelCase    (				self       ,  lowercase_=True)  -> Union[str, Any]:
											a__      =ConstraintListState(self.constraints)  # we actually never though self.constraints objects
											# throughout this process. So it's at initialization state.

											if stateful:
																		a__      =[
																		    constraint.copy(stateful=lowercase_) for constraint in self.complete_constraints
																		]
																		if self.inprogress_constraint is not None:
																									a__      =self.inprogress_constraint.copy(stateful=lowercase_)
																		a__      =[constraint.copy() for constraint in self.pending_constraints]

											return new_state





import unittest

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

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

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()




class       lowercase_					(lowercase__      ,					unittest.TestCase   ):
				snake_case	    =KandinskyVaaPriorPipeline
				snake_case	    =['prompt']
				snake_case	    =['prompt', 'negative_prompt']
				snake_case	    =[
				    'num_images_per_prompt',
				    'generator',
				    'num_inference_steps',
				    'latents',
				    'negative_prompt',
				    'guidance_scale',
				    'output_type',
				    'return_dict',
				]
				snake_case	    =False





				@property
				def 						__UpperCamelCase    (				self)  -> Optional[int]:
											return 32





				@property
				def 						__UpperCamelCase    (				self)  -> Tuple:
											return 32





				@property
				def 						__UpperCamelCase    (				self)  -> int:
											return self.time_input_dim





				@property
				def 						__UpperCamelCase    (				self)  -> str:
											return self.time_input_dim * 4





				@property
				def 						__UpperCamelCase    (				self)  -> Optional[int]:
											return 100





				@property
				def 						__UpperCamelCase    (				self)  -> Union[str, Any]:
											a__      =CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip')
											return tokenizer





				@property
				def 						__UpperCamelCase    (				self)  -> Union[str, Any]:
											torch.manual_seed(0)
											a__      =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=1000       ,  )
											return CLIPTextModelWithProjection(lowercase_)





				@property
				def 						__UpperCamelCase    (				self)  -> Tuple:
											torch.manual_seed(0)

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

											a__      =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
											a__      =nn.Parameter(torch.ones(model.clip_std.shape))
											return model





				@property
				def 						__UpperCamelCase    (				self)  -> Any:
											torch.manual_seed(0)
											a__      =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       ,  )

											a__      =CLIPVisionModelWithProjection(lowercase_)
											return model





				@property
				def 						__UpperCamelCase    (				self)  -> Optional[int]:
											a__      =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 						__UpperCamelCase    (				self)  -> Any:
											a__      =self.dummy_prior
											a__      =self.dummy_image_encoder
											a__      =self.dummy_text_encoder
											a__      =self.dummy_tokenizer
											a__      =self.dummy_image_processor

											a__      =UnCLIPScheduler(
											    variance_type='fixed_small_log'       ,  prediction_type='sample'       ,  num_train_timesteps=1000       ,  clip_sample=lowercase_       ,  clip_sample_range=10.0       ,  )

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

											return components





				def 						__UpperCamelCase    (				self       ,  lowercase_       ,  lowercase_=0)  -> Tuple:
											if str(lowercase_).startswith('mps'):
																		a__      =torch.manual_seed(lowercase_)
											else:
																		a__      =torch.Generator(device=lowercase_).manual_seed(lowercase_)
											a__      ={
											    'prompt': 'horse',
											    'generator': generator,
											    'guidance_scale': 4.0,
											    'num_inference_steps': 2,
											    'output_type': 'np',
											}
											return inputs





				def 						__UpperCamelCase    (				self)  -> int:
											a__      ='cpu'

											a__      =self.get_dummy_components()

											a__      =self.pipeline_class(**lowercase_)
											a__      =pipe.to(lowercase_)

											pipe.set_progress_bar_config(disable=lowercase_)

											a__      =pipe(**self.get_dummy_inputs(lowercase_))
											a__      =output.image_embeds

											a__      =pipe(
											    **self.get_dummy_inputs(lowercase_)       ,  return_dict=lowercase_       ,  )[0]

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

											assert image.shape == (1, 32)

											a__      =np.array(
											    [-0.05_32, 1.71_20, 0.36_56, -1.08_52, -0.89_46, -1.17_56, 0.43_48, 0.24_82, 0.51_46, -0.11_56])

											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 						__UpperCamelCase    (				self)  -> List[Any]:
											a__      =torch_device == 'cpu'
											a__      =True
											a__      =False

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





				@skip_mps
				def 						__UpperCamelCase    (				self)  -> Optional[int]:
											a__      =torch_device == 'cpu'
											a__      =False

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

