


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






class _lowerCamelCase(		_SCREAMING_SNAKE_CASE     ):
       def __init__(      self) ->     Optional[Any]:




           """simple docstring"""

           self.test()
       def     UpperCamelCase  (      self) ->     Dict:




           """simple docstring"""

           _lowercase :							Dict   	=	0
           _lowercase :							str   	=	False
           while not completed:
               if counter == 1:
                   self.reset()
               _lowercase :							Dict   	=	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 :							int   	=	self.update(A_)
               counter += 1

               if counter > 1_00_00:
                   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[Any]:




           """simple docstring"""

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




           """simple docstring"""

           raise NotImplementedError(
               F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''')
       @abstractmethod
       def     UpperCamelCase  (      self,   lowerCamelCase) ->     int:




           """simple docstring"""

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




           """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,   lowerCamelCase=False) ->     int:




           """simple docstring"""

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






class _lowerCamelCase(		_SCREAMING_SNAKE_CASE     ):
       def __init__(      self,   lowerCamelCase) ->     Any:




           """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 :							Optional[int]   	=	token_ids

           _lowercase :							List[Any]   	=	len(self.token_ids)
           _lowercase :							Optional[Any]   	=	-1  # the index of the currently fulfilled step
           _lowercase :							Union[str, Any]   	=	False
       def     UpperCamelCase  (      self) ->     Optional[Any]:




           """simple docstring"""

           if self.completed:
               return None
           return self.token_ids[self.fulfilled_idx + 1]
       def     UpperCamelCase  (      self,   lowerCamelCase) ->     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_)}''')

           if self.completed:
               return False

           return token_id == self.token_ids[self.fulfilled_idx + 1]
       def     UpperCamelCase  (      self,   lowerCamelCase) ->     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 :							str   	=	False
           _lowercase :							int   	=	False
           _lowercase :							List[Any]   	=	False

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




           """simple docstring"""

           _lowercase :							Any   	=	False
           _lowercase :							List[Any]   	=	0
       def     UpperCamelCase  (      self) ->     int:




           """simple docstring"""

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




       def     UpperCamelCase  (      self,   lowerCamelCase=False) ->     Union[str, Any]:




           """simple docstring"""

           _lowercase :							Any   	=	PhrasalConstraint(self.token_ids)

           if stateful:
               _lowercase :							int   	=	self.seqlen
               _lowercase :							List[str]   	=	self.fulfilled_idx
               _lowercase :							int   	=	self.completed

           return new_constraint






class _lowerCamelCase:
       def __init__(      self,   lowerCamelCase,   lowerCamelCase=True) ->     List[Any]:




           """simple docstring"""

           _lowercase :							int   	=	max([len(A_) for one in nested_token_ids])

           _lowercase :							Optional[Any]   	=	{}
           for token_ids in nested_token_ids:
               _lowercase :							Any   	=	root
               for tidx, token_id in enumerate(A_):
                   if token_id not in level:
                       _lowercase :							List[str]   	=	{}

                   _lowercase :							List[Any]   	=	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 :							Dict   	=	root
       def     UpperCamelCase  (      self,   lowerCamelCase) ->     Optional[Any]:




           """simple docstring"""

           _lowercase :							List[str]   	=	self.trie

           for current_token in current_seq:
               _lowercase :							Optional[int]   	=	start[current_token]

           _lowercase :							Optional[Any]   	=	list(start.keys())

           return next_tokens
       def     UpperCamelCase  (      self,   lowerCamelCase) ->     Union[str, Any]:




           """simple docstring"""

           _lowercase :							Optional[int]   	=	self.next_tokens(A_)

           return len(A_) == 0
       def     UpperCamelCase  (      self,   lowerCamelCase) ->     List[str]:




           """simple docstring"""

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




       def     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase) ->     Optional[int]:




           """simple docstring"""

           _lowercase :							Optional[Any]   	=	self.count_leaves(A_)
           return len(A_) != leaf_count






class _lowerCamelCase(		_SCREAMING_SNAKE_CASE     ):
       def __init__(      self,   lowerCamelCase) ->     str:




           """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 :							Optional[Any]   	=	DisjunctiveTrie(A_)
           _lowercase :							List[Any]   	=	nested_token_ids

           _lowercase :							Dict   	=	self.trie.max_height
           _lowercase :							str   	=	[]
           _lowercase :							List[str]   	=	False
       def     UpperCamelCase  (      self) ->     Union[str, Any]:




           """simple docstring"""

           _lowercase :							List[str]   	=	self.trie.next_tokens(self.current_seq)

           if len(A_) == 0:
               return None
           else:
               return token_list
       def     UpperCamelCase  (      self,   lowerCamelCase) ->     Optional[Any]:




           """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 :							Any   	=	self.trie.next_tokens(self.current_seq)

           return token_id in next_tokens
       def     UpperCamelCase  (      self,   lowerCamelCase) ->     Optional[Any]:




           """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 :							Any   	=	False
           _lowercase :							Optional[Any]   	=	False
           _lowercase :							Any   	=	False

           if self.does_advance(A_):
               self.current_seq.append(A_)
               _lowercase :							Optional[Any]   	=	True
           else:
               _lowercase :							List[Any]   	=	True
               self.reset()

           _lowercase :							List[Any]   	=	self.trie.reached_leaf(self.current_seq)
           _lowercase :							List[Any]   	=	completed

           return stepped, completed, reset
       def     UpperCamelCase  (      self) ->     str:




           """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,   lowerCamelCase=False) ->     int:




           """simple docstring"""

           _lowercase :							Union[str, Any]   	=	DisjunctiveConstraint(self.token_ids)

           if stateful:
               _lowercase :							int   	=	self.seqlen
               _lowercase :							Any   	=	self.current_seq
               _lowercase :							int   	=	self.completed

           return new_constraint






class _lowerCamelCase:
       def __init__(      self,   lowerCamelCase) ->     Tuple:




           """simple docstring"""

           _lowercase :							int   	=	constraints

           # max # of steps required to fulfill a given constraint
           _lowercase :							Optional[Any]   	=	max([c.seqlen for c in constraints])
           _lowercase :							Dict   	=	len(A_)
           _lowercase :							str   	=	False

           self.init_state()
       def     UpperCamelCase  (      self) ->     List[str]:




           """simple docstring"""

           _lowercase :							Optional[int]   	=	[]
           _lowercase :							Any   	=	None
           _lowercase :							int   	=	[constraint.copy(stateful=A_) for constraint in self.constraints]
       def     UpperCamelCase  (      self) ->     Optional[int]:




           """simple docstring"""

           _lowercase :							List[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) ->     Optional[int]:




           """simple docstring"""

           _lowercase :							Union[str, Any]   	=	[]
           if self.inprogress_constraint is None:
               for constraint in self.pending_constraints:  # "pending" == "unfulfilled yet"
                   _lowercase :							Optional[Any]   	=	constraint.advance()
                   if isinstance(A_,   A_):
                       token_list.append(A_)
                   elif isinstance(A_,   A_):
                       token_list.extend(A_)
           else:
               _lowercase :							Any   	=	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     UpperCamelCase  (      self,   lowerCamelCase) ->     Any:




           """simple docstring"""

           self.init_state()

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

                   # the entire list of constraints are fulfilled
                   if self.completed:
                       break
       def     UpperCamelCase  (      self,   lowerCamelCase) ->     int:




           """simple docstring"""

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

           _lowercase	,       _lowercase :							Union[str, Any]   	=	False, False

           if self.completed:
               _lowercase :							Any   	=	True
               _lowercase :							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

               _lowercase	,       _lowercase	,       _lowercase :							Dict   	=	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 :							Tuple   	=	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 :							Dict   	=	None

                   if len(self.pending_constraints) == 0:
                       # we're done!
                       _lowercase :							Optional[int]   	=	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 :							Union[str, Any]   	=	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 :							Tuple   	=	None

                       if not complete and stepped:
                           _lowercase :							List[Any]   	=	pending_constraint

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

                           _lowercase :							List[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.

                               _lowercase :							Tuple   	=	True

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

           return complete, stepped




       def     UpperCamelCase  (      self,   lowerCamelCase=True) ->     Tuple:




           """simple docstring"""

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

           if stateful:
               _lowercase :							Dict   	=	[
                   constraint.copy(stateful=A_) for constraint in self.complete_constraints
               ]
               if self.inprogress_constraint is not None:
                   _lowercase :							Optional[Any]   	=	self.inprogress_constraint.copy(stateful=A_)
               _lowercase :							Optional[Any]   	=	[constraint.copy() for constraint in self.pending_constraints]

           return new_state






def        UpperCamelCase_(   lowerCamelCase_				)					->		int:
    assert (
        isinstance(lowerCamelCase_							,				lowerCamelCase_				) and number_of_steps > 0
    ), F'''number_of_steps needs to be positive integer, your input {number_of_steps}'''
    if number_of_steps == 1:
        return 1
    _lowercase	,       _lowercase :							Dict   	=	1, 1
    for _ in range(number_of_steps - 1				):
        _lowercase	,       _lowercase :							Tuple   	=	current + previous, current
    return current


if __name__ == "__main__":
 import doctest

 doctest.testmod()


