


'''simple docstring'''







from abc import ABC, abstractmethod
from typing import List, Optional
class 	UpperCamelCase__					( SCREAMING_SNAKE_CASE_	):



     """simple docstring"""






     def __init__( self   ):

            '''simple docstring'''

            self.test()







     def a	( self   ):

            '''simple docstring'''

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

                   _lowerCAmelCase    :							Optional[Any]   			=       self.update(snake_case__   )
                   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 a	( self   ):

            '''simple docstring'''

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







     @abstractmethod
     def a	( self      ,	snake_case__   ):

            '''simple docstring'''

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







     @abstractmethod
     def a	( self      ,	snake_case__   ):

            '''simple docstring'''

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







     @abstractmethod
     def a	( self   ):

            '''simple docstring'''

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







     @abstractmethod
     def a	( self   ):

            '''simple docstring'''

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







     @abstractmethod
     def a	( self      ,	snake_case__=False   ):

            '''simple docstring'''

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



     """simple docstring"""






     def __init__( self      ,	snake_case__   ):

            '''simple docstring'''

            super(snake_case__      ,	self   ).__init__()

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

            _lowerCAmelCase    :							List[str]   			=       token_ids

            _lowerCAmelCase    :							Optional[Any]   			=       len(self.token_ids   )
            _lowerCAmelCase    :							List[str]   			=       -1  # the index of the currently fulfilled step
            _lowerCAmelCase    :							int   			=       False







     def a	( self   ):

            '''simple docstring'''

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







     def a	( self      ,	snake_case__   ):

            '''simple docstring'''

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

            if self.completed:
                   return False

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







     def a	( self      ,	snake_case__   ):

            '''simple docstring'''

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

            _lowerCAmelCase    :							Union[str, Any]   			=       False
            _lowerCAmelCase    :							int   			=       False
            _lowerCAmelCase    :							Optional[int]   			=       False

            if self.does_advance(snake_case__   ):
                   self.fulfilled_idx += 1
                   _lowerCAmelCase    :							str   			=       True
                   if self.fulfilled_idx == (self.seqlen - 1):
                          _lowerCAmelCase    :							Optional[int]   			=       True
                   _lowerCAmelCase    :							Dict   			=       completed
            else:
                   # failed to make progress.
                   _lowerCAmelCase    :							List[Any]   			=       True
                   self.reset()
            return stepped, completed, reset







     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							List[str]   			=       False
            _lowerCAmelCase    :							Optional[int]   			=       0







     def a	( self   ):

            '''simple docstring'''

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







     def a	( self      ,	snake_case__=False   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Union[str, Any]   			=       PhrasalConstraint(self.token_ids   )

            if stateful:
                   _lowerCAmelCase    :							Dict   			=       self.seqlen
                   _lowerCAmelCase    :							Optional[int]   			=       self.fulfilled_idx
                   _lowerCAmelCase    :							List[Any]   			=       self.completed

            return new_constraint
class 	UpperCamelCase__					:



     """simple docstring"""






     def __init__( self      ,	snake_case__      ,	snake_case__=True   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Any   			=       max([len(snake_case__   ) for one in nested_token_ids]   )

            _lowerCAmelCase    :							int   			=       {}
            for token_ids in nested_token_ids:
                   _lowerCAmelCase    :							Tuple   			=       root
                   for tidx, token_id in enumerate(snake_case__   ):
                          if token_id not in level:
                                 _lowerCAmelCase    :							Dict   			=       {}

                          _lowerCAmelCase    :							Tuple   			=       level[token_id]

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

            _lowerCAmelCase    :							Optional[int]   			=       root







     def a	( self      ,	snake_case__   ):

            '''simple docstring'''

            _lowerCAmelCase    :							List[str]   			=       self.trie

            for current_token in current_seq:
                   _lowerCAmelCase    :							List[Any]   			=       start[current_token]

            _lowerCAmelCase    :							Optional[int]   			=       list(start.keys()   )

            return next_tokens







     def a	( self      ,	snake_case__   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Dict   			=       self.next_tokens(snake_case__   )

            return len(snake_case__   ) == 0







     def a	( self      ,	snake_case__   ):

            '''simple docstring'''

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







     def a	( self      ,	snake_case__      ,	snake_case__   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Union[str, Any]   			=       self.count_leaves(snake_case__   )
            return len(snake_case__   ) != leaf_count
class 	UpperCamelCase__					( SCREAMING_SNAKE_CASE_	):



     """simple docstring"""






     def __init__( self      ,	snake_case__   ):

            '''simple docstring'''

            super(snake_case__      ,	self   ).__init__()

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

            _lowerCAmelCase    :							Dict   			=       DisjunctiveTrie(snake_case__   )
            _lowerCAmelCase    :							List[str]   			=       nested_token_ids

            _lowerCAmelCase    :							int   			=       self.trie.max_height
            _lowerCAmelCase    :							str   			=       []
            _lowerCAmelCase    :							str   			=       False







     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Tuple   			=       self.trie.next_tokens(self.current_seq   )

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







     def a	( self      ,	snake_case__   ):

            '''simple docstring'''

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

            _lowerCAmelCase    :							Optional[Any]   			=       self.trie.next_tokens(self.current_seq   )

            return token_id in next_tokens







     def a	( self      ,	snake_case__   ):

            '''simple docstring'''

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

            _lowerCAmelCase    :							str   			=       False
            _lowerCAmelCase    :							str   			=       False
            _lowerCAmelCase    :							Tuple   			=       False

            if self.does_advance(snake_case__   ):
                   self.current_seq.append(snake_case__   )
                   _lowerCAmelCase    :							List[str]   			=       True
            else:
                   _lowerCAmelCase    :							Optional[int]   			=       True
                   self.reset()

            _lowerCAmelCase    :							List[str]   			=       self.trie.reached_leaf(self.current_seq   )
            _lowerCAmelCase    :							Optional[Any]   			=       completed

            return stepped, completed, reset







     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Optional[Any]   			=       False
            _lowerCAmelCase    :							int   			=       []







     def a	( self   ):

            '''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 a	( self      ,	snake_case__=False   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Optional[Any]   			=       DisjunctiveConstraint(self.token_ids   )

            if stateful:
                   _lowerCAmelCase    :							List[str]   			=       self.seqlen
                   _lowerCAmelCase    :							Optional[int]   			=       self.current_seq
                   _lowerCAmelCase    :							Tuple   			=       self.completed

            return new_constraint
class 	UpperCamelCase__					:



     """simple docstring"""






     def __init__( self      ,	snake_case__   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Optional[Any]   			=       constraints

            # max # of steps required to fulfill a given constraint
            _lowerCAmelCase    :							List[str]   			=       max([c.seqlen for c in constraints]   )
            _lowerCAmelCase    :							int   			=       len(snake_case__   )
            _lowerCAmelCase    :							Dict   			=       False

            self.init_state()







     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Optional[int]   			=       []
            _lowerCAmelCase    :							str   			=       None
            _lowerCAmelCase    :							Optional[Any]   			=       [constraint.copy(stateful=snake_case__   ) for constraint in self.constraints]







     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							int   			=       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 a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Union[str, Any]   			=       []
            if self.inprogress_constraint is None:
                   for constraint in self.pending_constraints:  # "pending" == "unfulfilled yet"
                          _lowerCAmelCase    :							Any   			=       constraint.advance()
                          if isinstance(snake_case__      ,	snake_case__   ):
                                 token_list.append(snake_case__   )
                          elif isinstance(snake_case__      ,	snake_case__   ):
                                 token_list.extend(snake_case__   )
            else:
                   _lowerCAmelCase    :							Optional[Any]   			=       self.inprogress_constraint.advance()
                   if isinstance(snake_case__      ,	snake_case__   ):
                          token_list.append(snake_case__   )
                   elif isinstance(snake_case__      ,	snake_case__   ):
                          token_list.extend(snake_case__   )

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







     def a	( self      ,	snake_case__   ):

            '''simple docstring'''

            self.init_state()

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

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







     def a	( self      ,	snake_case__   ):

            '''simple docstring'''

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

            _lowerCAmelCase    :							List[Any]   			=       False, False

            if self.completed:
                   _lowerCAmelCase    :							List[Any]   			=       True
                   _lowerCAmelCase    :							List[Any]   			=       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

                   _lowerCAmelCase    :							int   			=       self.inprogress_constraint.update(snake_case__   )
                   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=snake_case__   )   )
                          _lowerCAmelCase    :							int   			=       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   )
                          _lowerCAmelCase    :							Optional[int]   			=       None

                          if len(self.pending_constraints   ) == 0:
                                 # we're done!
                                 _lowerCAmelCase    :							Tuple   			=       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(snake_case__   ):
                                 _lowerCAmelCase    :							str   			=       pending_constraint.update(snake_case__   )

                                 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(snake_case__   )
                                        _lowerCAmelCase    :							str   			=       None

                                 if not complete and stepped:
                                        _lowerCAmelCase    :							int   			=       pending_constraint

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

                                        _lowerCAmelCase    :							Any   			=       (
                                            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.

                                               _lowerCAmelCase    :							List[str]   			=       True

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

            return complete, stepped







     def a	( self      ,	snake_case__=True   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Union[str, Any]   			=       ConstraintListState(self.constraints   )  # we actually never though self.constraints objects
            # throughout this process. So it's at initialization state.

            if stateful:
                   _lowerCAmelCase    :							List[str]   			=       [
                       constraint.copy(stateful=snake_case__   ) for constraint in self.complete_constraints
                   ]
                   if self.inprogress_constraint is not None:
                          _lowerCAmelCase    :							str   			=       self.inprogress_constraint.copy(stateful=snake_case__   )
                   _lowerCAmelCase    :							List[str]   			=       [constraint.copy() for constraint in self.pending_constraints]

            return new_state






'''simple docstring'''







from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


lowerCAmelCase    :     Any					=						{
    """configuration_x_clip""": [
        """XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""",
        """XCLIPConfig""",
        """XCLIPTextConfig""",
        """XCLIPVisionConfig""",
    ],
    """processing_x_clip""": ["""XCLIPProcessor"""],
}

try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       lowerCAmelCase    :     Optional[Any]					=						[
           """XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST""",
           """XCLIPModel""",
           """XCLIPPreTrainedModel""",
           """XCLIPTextModel""",
           """XCLIPVisionModel""",
       ]

if TYPE_CHECKING:
       from .configuration_x_clip import (
           XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
           XCLIPConfig,
           XCLIPTextConfig,
           XCLIPVisionConfig,
       )
       from .processing_x_clip import XCLIPProcessor

       try:
              if not is_torch_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_x_clip import (
                  XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
                  XCLIPModel,
                  XCLIPPreTrainedModel,
                  XCLIPTextModel,
                  XCLIPVisionModel,
              )

else:
       import sys

       lowerCAmelCase    :     Dict					=						_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)

