





'''simple docstring'''





from abc import ABC, abstractmethod
from typing import List, Optional
class        SCREAMING_SNAKE_CASE     (UpperCAmelCase   ):


   def __init__(					self    :       Dict )->     Dict:





     """simple docstring"""







     self.test()


   def  SCREAMING_SNAKE_CASE_							(					self    :       Tuple )->     str:





     """simple docstring"""







     lowercase__			    =						0
     lowercase__			    =						False
     while not completed:
       if counter == 1:
         self.reset()
       lowercase__			    =						self.advance()
       if not self.does_advance(a ):
         raise Exception(
             'Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.' )

       lowercase__    ,					lowercase__    ,					lowercase__			    =						self.update(a )
       counter += 1

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

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


   @abstractmethod
   def  SCREAMING_SNAKE_CASE_							(					self    :       str )->     Any:





     """simple docstring"""







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


   @abstractmethod
   def  SCREAMING_SNAKE_CASE_							(					self    :       Optional[int]    ,  a    :       int )->     int:





     """simple docstring"""







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


   @abstractmethod
   def  SCREAMING_SNAKE_CASE_							(					self    :       Optional[Any]    ,  a    :       int )->     Tuple:





     """simple docstring"""







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


   @abstractmethod
   def  SCREAMING_SNAKE_CASE_							(					self    :       List[Any] )->     Any:





     """simple docstring"""







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


   @abstractmethod
   def  SCREAMING_SNAKE_CASE_							(					self    :       List[str] )->     Dict:





     """simple docstring"""







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


   @abstractmethod
   def  SCREAMING_SNAKE_CASE_							(					self    :       int    ,  a    :       Tuple=False )->     Optional[int]:





     """simple docstring"""







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






class        SCREAMING_SNAKE_CASE     (UpperCAmelCase   ):


   def __init__(					self    :       Optional[int]    ,  a    :       List[int] )->     List[str]:





     """simple docstring"""







     super(a    ,  self ).__init__()

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

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


   def  SCREAMING_SNAKE_CASE_							(					self    :       Optional[Any] )->     Dict:





     """simple docstring"""







     if self.completed:
       return None
     return self.token_ids[self.fulfilled_idx + 1]


   def  SCREAMING_SNAKE_CASE_							(					self    :       List[Any]    ,  a    :       int )->     List[str]:





     """simple docstring"""







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

     if self.completed:
       return False

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


   def  SCREAMING_SNAKE_CASE_							(					self    :       Optional[int]    ,  a    :       int )->     Optional[int]:





     """simple docstring"""







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

     lowercase__			    =						False
     lowercase__			    =						False
     lowercase__			    =						False

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


   def  SCREAMING_SNAKE_CASE_							(					self    :       Dict )->     Union[str, Any]:





     """simple docstring"""







     lowercase__			    =						False
     lowercase__			    =						0


   def  SCREAMING_SNAKE_CASE_							(					self    :       int )->     List[str]:





     """simple docstring"""







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


   def  SCREAMING_SNAKE_CASE_							(					self    :       Dict    ,  a    :       str=False )->     int:





     """simple docstring"""







     lowercase__			    =						PhrasalConstraint(self.token_ids )

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

     return new_constraint






class        SCREAMING_SNAKE_CASE     :


   def __init__(					self    :       Optional[Any]    ,  a    :       List[List[int]]    ,  a    :       Dict=True )->     Optional[int]:





     """simple docstring"""







     lowercase__			    =						max([len(a ) for one in nested_token_ids] )

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

         lowercase__			    =						level[token_id]

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

     lowercase__			    =						root


   def  SCREAMING_SNAKE_CASE_							(					self    :       Dict    ,  a    :       Optional[int] )->     List[Any]:





     """simple docstring"""







     lowercase__			    =						self.trie

     for current_token in current_seq:
       lowercase__			    =						start[current_token]

     lowercase__			    =						list(start.keys() )

     return next_tokens


   def  SCREAMING_SNAKE_CASE_							(					self    :       int    ,  a    :       Dict )->     Tuple:





     """simple docstring"""







     lowercase__			    =						self.next_tokens(a )

     return len(a ) == 0


   def  SCREAMING_SNAKE_CASE_							(					self    :       Dict    ,  a    :       Any )->     Optional[int]:





     """simple docstring"""







     lowercase__			    =						list(root.values() )
     if len(a ) == 0:
       return 1
     else:
       return sum([self.count_leaves(a ) for nn in next_nodes] )


   def  SCREAMING_SNAKE_CASE_							(					self    :       Optional[int]    ,  a    :       str    ,  a    :       int )->     Union[str, Any]:





     """simple docstring"""







     lowercase__			    =						self.count_leaves(a )
     return len(a ) != leaf_count






class        SCREAMING_SNAKE_CASE     (UpperCAmelCase   ):


   def __init__(					self    :       List[Any]    ,  a    :       List[List[int]] )->     int:





     """simple docstring"""







     super(a    ,  self ).__init__()

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

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


   def  SCREAMING_SNAKE_CASE_							(					self    :       Dict )->     Union[str, Any]:





     """simple docstring"""







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

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


   def  SCREAMING_SNAKE_CASE_							(					self    :       List[str]    ,  a    :       int )->     int:





     """simple docstring"""







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

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

     return token_id in next_tokens


   def  SCREAMING_SNAKE_CASE_							(					self    :       Optional[Any]    ,  a    :       int )->     Tuple:





     """simple docstring"""







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

     lowercase__			    =						False
     lowercase__			    =						False
     lowercase__			    =						False

     if self.does_advance(a ):
       self.current_seq.append(a )
       lowercase__			    =						True
     else:
       lowercase__			    =						True
       self.reset()

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

     return stepped, completed, reset


   def  SCREAMING_SNAKE_CASE_							(					self    :       str )->     List[Any]:





     """simple docstring"""







     lowercase__			    =						False
     lowercase__			    =						[]


   def  SCREAMING_SNAKE_CASE_							(					self    :       Dict )->     str:





     """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  SCREAMING_SNAKE_CASE_							(					self    :       int    ,  a    :       Any=False )->     Optional[Any]:





     """simple docstring"""







     lowercase__			    =						DisjunctiveConstraint(self.token_ids )

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

     return new_constraint






class        SCREAMING_SNAKE_CASE     :


   def __init__(					self    :       Tuple    ,  a    :       List[Constraint] )->     int:





     """simple docstring"""







     lowercase__			    =						constraints

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

     self.init_state()


   def  SCREAMING_SNAKE_CASE_							(					self    :       Optional[Any] )->     Dict:





     """simple docstring"""







     lowercase__			    =						[]
     lowercase__			    =						None
     lowercase__			    =						[constraint.copy(stateful=a ) for constraint in self.constraints]


   def  SCREAMING_SNAKE_CASE_							(					self    :       Optional[Any] )->     List[str]:





     """simple docstring"""







     lowercase__			    =						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  SCREAMING_SNAKE_CASE_							(					self    :       Any )->     List[Any]:





     """simple docstring"""







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

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


   def  SCREAMING_SNAKE_CASE_							(					self    :       str    ,  a    :       Optional[List[int]] )->     str:





     """simple docstring"""







     self.init_state()

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

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


   def  SCREAMING_SNAKE_CASE_							(					self    :       str    ,  a    :       int )->     Dict:





     """simple docstring"""







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

     lowercase__    ,					lowercase__			    =						False, False

     if self.completed:
       lowercase__			    =						True
       lowercase__			    =						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__			    =						self.inprogress_constraint.update(a )
       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=a ) )
         lowercase__			    =						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__			    =						None

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

           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(a )
             lowercase__			    =						None

           if not complete and stepped:
             lowercase__			    =						pending_constraint

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

             lowercase__			    =						(
                 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__			    =						True

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

     return complete, stepped


   def  SCREAMING_SNAKE_CASE_							(					self    :       str    ,  a    :       str=True )->     str:





     """simple docstring"""







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

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

     return new_state









import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionPipeline
from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device


lowercase_					     =	False
class        SCREAMING_SNAKE_CASE     (unittest.TestCase   ):
   pass






@nightly
@require_torch_gpu
class        SCREAMING_SNAKE_CASE     (unittest.TestCase   ):


   def  SCREAMING_SNAKE_CASE_							(					self    :       str )->     Optional[int]:





     """simple docstring"""







     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()


   def  SCREAMING_SNAKE_CASE_							(					self    :       Optional[Any] )->     Union[str, Any]:





     """simple docstring"""







     lowercase__			    =						VersatileDiffusionPipeline.from_pretrained('shi-labs/versatile-diffusion'    ,  torch_dtype=torch.floataa )
     pipe.to(a )
     pipe.set_progress_bar_config(disable=a )

     lowercase__			    =						load_image(
         'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg' )

     lowercase__			    =						torch.manual_seed(0 )
     lowercase__			    =						pipe.dual_guided(
         prompt='first prompt'    ,  image=a    ,  text_to_image_strength=0.75    ,  generator=a    ,  guidance_scale=7.5    ,  num_inference_steps=2    ,  output_type='numpy'    ,  ).images

     with tempfile.TemporaryDirectory() as tmpdirname:
       pipe.save_pretrained(a )
       lowercase__			    =						VersatileDiffusionPipeline.from_pretrained(a    ,  torch_dtype=torch.floataa )
     pipe.to(a )
     pipe.set_progress_bar_config(disable=a )

     lowercase__			    =						generator.manual_seed(0 )
     lowercase__			    =						pipe.dual_guided(
         prompt='first prompt'    ,  image=a    ,  text_to_image_strength=0.75    ,  generator=a    ,  guidance_scale=7.5    ,  num_inference_steps=2    ,  output_type='numpy'    ,  ).images

     assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass"


   def  SCREAMING_SNAKE_CASE_							(					self    :       Tuple )->     List[str]:





     """simple docstring"""







     lowercase__			    =						VersatileDiffusionPipeline.from_pretrained('shi-labs/versatile-diffusion'    ,  torch_dtype=torch.floataa )
     pipe.to(a )
     pipe.set_progress_bar_config(disable=a )

     lowercase__			    =						'cyberpunk 2077'
     lowercase__			    =						load_image(
         'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg' )
     lowercase__			    =						torch.manual_seed(0 )
     lowercase__			    =						pipe.dual_guided(
         prompt=a    ,  image=a    ,  text_to_image_strength=0.75    ,  generator=a    ,  guidance_scale=7.5    ,  num_inference_steps=50    ,  output_type='numpy'    ,  ).images

     lowercase__			    =						image[0, 253:256, 253:256, -1]

     assert image.shape == (1, 512, 512, 3)
     lowercase__			    =						np.array([0.1448, 0.1619, 0.1741, 0.1086, 0.1147, 0.1128, 0.1199, 0.1165, 0.1001] )

     assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1

     lowercase__			    =						'A painting of a squirrel eating a burger '
     lowercase__			    =						torch.manual_seed(0 )
     lowercase__			    =						pipe.text_to_image(
         prompt=a    ,  generator=a    ,  guidance_scale=7.5    ,  num_inference_steps=50    ,  output_type='numpy' ).images

     lowercase__			    =						image[0, 253:256, 253:256, -1]

     assert image.shape == (1, 512, 512, 3)
     lowercase__			    =						np.array([0.3367, 0.3169, 0.2656, 0.3870, 0.4790, 0.3796, 0.4009, 0.4878, 0.4778] )

     assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1

     lowercase__			    =						pipe.image_variation(a    ,  generator=a    ,  output_type='numpy' ).images

     lowercase__			    =						image[0, 253:256, 253:256, -1]

     assert image.shape == (1, 512, 512, 3)
     lowercase__			    =						np.array([0.3076, 0.3123, 0.3284, 0.3782, 0.3770, 0.3894, 0.4297, 0.4331, 0.4456] )

     assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1


