"""simple docstring"""







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







class  UpperCamelCase	(    lowercase_						):
   def __init__(    self    )			->   List[str]:


        '''simple docstring'''


        self.test()
   def     _UpperCAmelCase     (    self    )			->   Any:


        '''simple docstring'''


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

             lowercase_							,						lowercase_							,						lowercase_			:       Optional[int]									=			self.update(__UpperCamelCase    )
             counter += 1

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

        if self.remaining() != 0:
             raise Exception('Custom Constraint is not defined correctly.'    )
   @abstractmethod
   def     _UpperCAmelCase     (    self    )			->   List[Any]:


        '''simple docstring'''


        raise NotImplementedError(
            f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''    )
   @abstractmethod
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase    )			->   Any:


        '''simple docstring'''


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


        '''simple docstring'''


        raise NotImplementedError(
            f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''    )
   @abstractmethod
   def     _UpperCAmelCase     (    self    )			->   str:


        '''simple docstring'''


        raise NotImplementedError(
            f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''    )
   @abstractmethod
   def     _UpperCAmelCase     (    self    )			->   Union[str, Any]:


        '''simple docstring'''


        raise NotImplementedError(
            f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''    )







   @abstractmethod
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase=False    )			->   Dict:


        '''simple docstring'''


        raise NotImplementedError(
            f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''    )







class  UpperCamelCase	(    lowercase_						):
   def __init__(    self  ,__UpperCamelCase    )			->   Dict:


        '''simple docstring'''


        super(__UpperCamelCase  ,self    ).__init__()

        if not isinstance(__UpperCamelCase  ,__UpperCamelCase    ) or len(__UpperCamelCase    ) == 0:
             raise ValueError(f'''`token_ids` has to be a non-empty list, but is {token_ids}.'''    )
        if any((not isinstance(__UpperCamelCase  ,__UpperCamelCase    ) 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}.'''    )

        lowercase_			:       Union[str, Any]									=			token_ids

        lowercase_			:       List[str]									=			len(self.token_ids    )
        lowercase_			:       Dict									=			-1  # the index of the currently fulfilled step
        lowercase_			:       int									=			False
   def     _UpperCAmelCase     (    self    )			->   List[Any]:


        '''simple docstring'''


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


        '''simple docstring'''


        if not isinstance(__UpperCamelCase  ,__UpperCamelCase    ):
             raise ValueError(f'''`token_id` has to be an `int`, but is {token_id} of type {type(__UpperCamelCase    )}'''    )

        if self.completed:
             return False

        return token_id == self.token_ids[self.fulfilled_idx + 1]
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase    )			->   str:


        '''simple docstring'''


        if not isinstance(__UpperCamelCase  ,__UpperCamelCase    ):
             raise ValueError(f'''`token_id` has to be an `int`, but is {token_id} of type {type(__UpperCamelCase    )}'''    )

        lowercase_			:       str									=			False
        lowercase_			:       Dict									=			False
        lowercase_			:       str									=			False

        if self.does_advance(__UpperCamelCase    ):
             self.fulfilled_idx += 1
             lowercase_			:       Any									=			True
             if self.fulfilled_idx == (self.seqlen - 1):
                  lowercase_			:       Optional[Any]									=			True
             lowercase_			:       Dict									=			completed
        else:
             # failed to make progress.
             lowercase_			:       Any									=			True
             self.reset()
        return stepped, completed, reset
   def     _UpperCAmelCase     (    self    )			->   Dict:


        '''simple docstring'''


        lowercase_			:       List[str]									=			False
        lowercase_			:       Any									=			0
   def     _UpperCAmelCase     (    self    )			->   Any:


        '''simple docstring'''


        return self.seqlen - (self.fulfilled_idx + 1)







   def     _UpperCAmelCase     (    self  ,__UpperCamelCase=False    )			->   Optional[Any]:


        '''simple docstring'''


        lowercase_			:       Any									=			PhrasalConstraint(self.token_ids    )

        if stateful:
             lowercase_			:       Optional[int]									=			self.seqlen
             lowercase_			:       Tuple									=			self.fulfilled_idx
             lowercase_			:       Union[str, Any]									=			self.completed

        return new_constraint







class  UpperCamelCase	:
   def __init__(    self  ,__UpperCamelCase  ,__UpperCamelCase=True    )			->   Dict:


        '''simple docstring'''


        lowercase_			:       Optional[int]									=			max([len(__UpperCamelCase    ) for one in nested_token_ids]    )

        lowercase_			:       str									=			{}
        for token_ids in nested_token_ids:
             lowercase_			:       Dict									=			root
             for tidx, token_id in enumerate(__UpperCamelCase    ):
                  if token_id not in level:
                       lowercase_			:       List[Any]									=			{}

                  lowercase_			:       Optional[Any]									=			level[token_id]

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

        lowercase_			:       Optional[int]									=			root
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase    )			->   int:


        '''simple docstring'''


        lowercase_			:       int									=			self.trie

        for current_token in current_seq:
             lowercase_			:       Optional[Any]									=			start[current_token]

        lowercase_			:       int									=			list(start.keys()    )

        return next_tokens
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase    )			->   int:


        '''simple docstring'''


        lowercase_			:       Optional[Any]									=			self.next_tokens(__UpperCamelCase    )

        return len(__UpperCamelCase    ) == 0
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase    )			->   Optional[int]:


        '''simple docstring'''


        lowercase_			:       Optional[Any]									=			list(root.values()    )
        if len(__UpperCamelCase    ) == 0:
             return 1
        else:
             return sum([self.count_leaves(__UpperCamelCase    ) for nn in next_nodes]    )







   def     _UpperCAmelCase     (    self  ,__UpperCamelCase  ,__UpperCamelCase    )			->   Any:


        '''simple docstring'''


        lowercase_			:       Tuple									=			self.count_leaves(__UpperCamelCase    )
        return len(__UpperCamelCase    ) != leaf_count







class  UpperCamelCase	(    lowercase_						):
   def __init__(    self  ,__UpperCamelCase    )			->   Dict:


        '''simple docstring'''


        super(__UpperCamelCase  ,self    ).__init__()

        if not isinstance(__UpperCamelCase  ,__UpperCamelCase    ) or len(__UpperCamelCase    ) == 0:
             raise ValueError(f'''`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.'''    )
        if any(not isinstance(__UpperCamelCase  ,__UpperCamelCase    ) 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(__UpperCamelCase  ,__UpperCamelCase    ) 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}.'''    )

        lowercase_			:       Tuple									=			DisjunctiveTrie(__UpperCamelCase    )
        lowercase_			:       Any									=			nested_token_ids

        lowercase_			:       List[str]									=			self.trie.max_height
        lowercase_			:       Optional[Any]									=			[]
        lowercase_			:       Optional[Any]									=			False
   def     _UpperCAmelCase     (    self    )			->   Dict:


        '''simple docstring'''


        lowercase_			:       List[Any]									=			self.trie.next_tokens(self.current_seq    )

        if len(__UpperCamelCase    ) == 0:
             return None
        else:
             return token_list
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase    )			->   Union[str, Any]:


        '''simple docstring'''


        if not isinstance(__UpperCamelCase  ,__UpperCamelCase    ):
             raise ValueError(f'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(__UpperCamelCase    )}'''    )

        lowercase_			:       List[Any]									=			self.trie.next_tokens(self.current_seq    )

        return token_id in next_tokens
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase    )			->   Tuple:


        '''simple docstring'''


        if not isinstance(__UpperCamelCase  ,__UpperCamelCase    ):
             raise ValueError(f'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(__UpperCamelCase    )}'''    )

        lowercase_			:       str									=			False
        lowercase_			:       Union[str, Any]									=			False
        lowercase_			:       Dict									=			False

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

        lowercase_			:       Union[str, Any]									=			self.trie.reached_leaf(self.current_seq    )
        lowercase_			:       int									=			completed

        return stepped, completed, reset
   def     _UpperCAmelCase     (    self    )			->   Tuple:


        '''simple docstring'''


        lowercase_			:       Union[str, Any]									=			False
        lowercase_			:       Optional[int]									=			[]
   def     _UpperCAmelCase     (    self    )			->   Optional[int]:


        '''simple docstring'''


        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  ,__UpperCamelCase=False    )			->   Optional[int]:


        '''simple docstring'''


        lowercase_			:       List[str]									=			DisjunctiveConstraint(self.token_ids    )

        if stateful:
             lowercase_			:       Dict									=			self.seqlen
             lowercase_			:       Union[str, Any]									=			self.current_seq
             lowercase_			:       Optional[Any]									=			self.completed

        return new_constraint







class  UpperCamelCase	:
   def __init__(    self  ,__UpperCamelCase    )			->   List[str]:


        '''simple docstring'''


        lowercase_			:       Optional[Any]									=			constraints

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

        self.init_state()
   def     _UpperCAmelCase     (    self    )			->   Any:


        '''simple docstring'''


        lowercase_			:       Union[str, Any]									=			[]
        lowercase_			:       Union[str, Any]									=			None
        lowercase_			:       List[Any]									=			[constraint.copy(stateful=__UpperCamelCase    ) for constraint in self.constraints]
   def     _UpperCAmelCase     (    self    )			->   int:


        '''simple docstring'''


        lowercase_			:       Optional[Any]									=			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    )			->   List[str]:


        '''simple docstring'''


        lowercase_			:       int									=			[]
        if self.inprogress_constraint is None:
             for constraint in self.pending_constraints:  # "pending" == "unfulfilled yet"
                  lowercase_			:       int									=			constraint.advance()
                  if isinstance(__UpperCamelCase  ,__UpperCamelCase    ):
                       token_list.append(__UpperCamelCase    )
                  elif isinstance(__UpperCamelCase  ,__UpperCamelCase    ):
                       token_list.extend(__UpperCamelCase    )
        else:
             lowercase_			:       int									=			self.inprogress_constraint.advance()
             if isinstance(__UpperCamelCase  ,__UpperCamelCase    ):
                  token_list.append(__UpperCamelCase    )
             elif isinstance(__UpperCamelCase  ,__UpperCamelCase    ):
                  token_list.extend(__UpperCamelCase    )

        if len(__UpperCamelCase    ) == 0:
             return None
        else:
             return token_list
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase    )			->   str:


        '''simple docstring'''


        self.init_state()

        if token_ids is not None:
             for token in token_ids:
                  # completes or steps **one** constraint
                  lowercase_							,						lowercase_			:       Union[str, Any]									=			self.add(__UpperCamelCase    )

                  # the entire list of constraints are fulfilled
                  if self.completed:
                       break
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase    )			->   Any:


        '''simple docstring'''


        if not isinstance(__UpperCamelCase  ,__UpperCamelCase    ):
             raise ValueError(f'''`token_id` should be an `int`, but is `{token_id}`.'''    )

        lowercase_							,						lowercase_			:       Any									=			False, False

        if self.completed:
             lowercase_			:       int									=			True
             lowercase_			:       Dict									=			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

             lowercase_							,						lowercase_							,						lowercase_			:       str									=			self.inprogress_constraint.update(__UpperCamelCase    )
             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=__UpperCamelCase    )    )
                  lowercase_			:       List[str]									=			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    )
                  lowercase_			:       Optional[int]									=			None

                  if len(self.pending_constraints    ) == 0:
                       # we're done!
                       lowercase_			:       str									=			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(__UpperCamelCase    ):
                       lowercase_							,						lowercase_							,						lowercase_			:       int									=			pending_constraint.update(__UpperCamelCase    )

                       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(__UpperCamelCase    )
                            lowercase_			:       str									=			None

                       if not complete and stepped:
                            lowercase_			:       Optional[int]									=			pending_constraint

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

                            lowercase_			:       Optional[int]									=			(
                                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.

                                 lowercase_			:       Dict									=			True

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

        return complete, stepped







   def     _UpperCAmelCase     (    self  ,__UpperCamelCase=True    )			->   int:


        '''simple docstring'''


        lowercase_			:       Tuple									=			ConstraintListState(self.constraints    )  # we actually never though self.constraints objects
        # throughout this process. So it's at initialization state.

        if stateful:
             lowercase_			:       Tuple									=			[
                 constraint.copy(stateful=__UpperCamelCase    ) for constraint in self.complete_constraints
             ]
             if self.inprogress_constraint is not None:
                  lowercase_			:       Dict									=			self.inprogress_constraint.copy(stateful=__UpperCamelCase    )
             lowercase_			:       Optional[int]									=			[constraint.copy() for constraint in self.pending_constraints]

        return new_state


"""simple docstring"""







import random
import unittest

import torch

from diffusers import IFImgaImgSuperResolutionPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin







@skip_mps
class  UpperCamelCase	(    lowercase_		,   lowercase_		,   unittest.TestCase						):
   lowercase							=						IFImgaImgSuperResolutionPipeline
   lowercase							=						TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'width', 'height'}
   lowercase							=						TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'original_image'}						)
   lowercase							=						PipelineTesterMixin.required_optional_params - {'latents'}
   def     _UpperCAmelCase     (    self    )			->   int:


        '''simple docstring'''


        return self._get_superresolution_dummy_components()
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase  ,__UpperCamelCase=0    )			->   List[str]:


        '''simple docstring'''


        if str(__UpperCamelCase    ).startswith('mps'    ):
             lowercase_			:       Any									=			torch.manual_seed(__UpperCamelCase    )
        else:
             lowercase_			:       int									=			torch.Generator(device=__UpperCamelCase    ).manual_seed(__UpperCamelCase    )

        lowercase_			:       Optional[int]									=			floats_tensor((1, 3, 32, 32)  ,rng=random.Random(__UpperCamelCase    )    ).to(__UpperCamelCase    )
        lowercase_			:       List[str]									=			floats_tensor((1, 3, 16, 16)  ,rng=random.Random(__UpperCamelCase    )    ).to(__UpperCamelCase    )

        lowercase_			:       Optional[Any]									=			{
            'prompt': 'A painting of a squirrel eating a burger',
            'image': image,
            'original_image': original_image,
            'generator': generator,
            'num_inference_steps': 2,
            'output_type': 'numpy',
        }

        return inputs
   @unittest.skipIf(
       torch_device != 'cuda' or not is_xformers_available()  ,reason='XFormers attention is only available with CUDA and `xformers` installed'  ,)
   def     _UpperCAmelCase     (    self    )			->   Optional[Any]:


        '''simple docstring'''


        self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3    )
   def     _UpperCAmelCase     (    self    )			->   Dict:


        '''simple docstring'''


        self._test_save_load_optional_components()
   @unittest.skipIf(torch_device != 'cuda'  ,reason='float16 requires CUDA'    )
   def     _UpperCAmelCase     (    self    )			->   Optional[int]:


        '''simple docstring'''


        super().test_save_load_floataa(expected_max_diff=1e-1    )
   def     _UpperCAmelCase     (    self    )			->   Dict:


        '''simple docstring'''


        self._test_attention_slicing_forward_pass(expected_max_diff=1e-2    )
   def     _UpperCAmelCase     (    self    )			->   List[Any]:


        '''simple docstring'''


        self._test_save_load_local()







   def     _UpperCAmelCase     (    self    )			->   List[Any]:


        '''simple docstring'''


        self._test_inference_batch_single_identical(
            expected_max_diff=1e-2  ,)

