





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

class        snake_case__    (A__		):







						"""simple docstring"""




						def __init__(       self  ) ->				int:
									"""simple docstring"""




									self.test()

						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				Optional[Any]:
									"""simple docstring"""




									a__       :						Optional[Any]							=  0
									a__       :						List[str]							=  False
									while not completed:
												if counter == 1:
															self.reset()
												a__       :						Dict							=  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__       :						str							=  self.update(__lowercase  )
												counter += 1

												if counter > 1_0_0_0_0:
															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  ) ->				List[str]:
									"""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 ,       __lowercase  ) ->				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 ,       __lowercase  ) ->				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]:
									"""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  ) ->				str:
									"""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 ,       __lowercase=False  ) ->				Dict:
									"""simple docstring"""




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




class        snake_case__    (A__		):







						"""simple docstring"""




						def __init__(       self ,       __lowercase  ) ->				Union[str, Any]:
									"""simple docstring"""




									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__       :						List[Any]							=  token_ids

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

						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				List[Any]:
									"""simple docstring"""




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

						def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase  ) ->				Tuple:
									"""simple docstring"""




									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 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase  ) ->				str:
									"""simple docstring"""




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

									a__       :						Optional[int]							=  False
									a__       :						str							=  False
									a__       :						str							=  False

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

						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				Tuple:
									"""simple docstring"""




									a__       :						List[str]							=  False
									a__       :						int							=  0

						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				Tuple:
									"""simple docstring"""




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

						def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase=False  ) ->				Tuple:
									"""simple docstring"""




									a__       :						Tuple							=  PhrasalConstraint(self.token_ids  )

									if stateful:
												a__       :						Optional[Any]							=  self.seqlen
												a__       :						int							=  self.fulfilled_idx
												a__       :						Any							=  self.completed

									return new_constraint




class        snake_case__    :







						"""simple docstring"""




						def __init__(       self ,       __lowercase ,       __lowercase=True  ) ->				Any:
									"""simple docstring"""




									a__       :						List[Any]							=  max([len(__lowercase  ) for one in nested_token_ids]  )

									a__       :						Any							=  {}
									for token_ids in nested_token_ids:
												a__       :						int							=  root
												for tidx, token_id in enumerate(__lowercase  ):
															if token_id not in level:
																		a__       :						List[Any]							=  {}

															a__       :						Union[str, Any]							=  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__       :						Any							=  root

						def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase  ) ->				Optional[int]:
									"""simple docstring"""




									a__       :						Any							=  self.trie

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

									a__       :						Union[str, Any]							=  list(start.keys()  )

									return next_tokens

						def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase  ) ->				Tuple:
									"""simple docstring"""




									a__       :						int							=  self.next_tokens(__lowercase  )

									return len(__lowercase  ) == 0

						def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase  ) ->				Union[str, Any]:
									"""simple docstring"""




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

						def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase ,       __lowercase  ) ->				str:
									"""simple docstring"""




									a__       :						str							=  self.count_leaves(__lowercase  )
									return len(__lowercase  ) != leaf_count




class        snake_case__    (A__		):







						"""simple docstring"""




						def __init__(       self ,       __lowercase  ) ->				Any:
									"""simple docstring"""




									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__       :						Tuple							=  DisjunctiveTrie(__lowercase  )
									a__       :						Any							=  nested_token_ids

									a__       :						List[Any]							=  self.trie.max_height
									a__       :						str							=  []
									a__       :						Optional[int]							=  False

						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				Optional[int]:
									"""simple docstring"""




									a__       :						Union[str, Any]							=  self.trie.next_tokens(self.current_seq  )

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

						def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase  ) ->				int:
									"""simple docstring"""




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

									return token_id in next_tokens

						def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase  ) ->				Dict:
									"""simple docstring"""




									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__       :						Any							=  False
									a__       :						List[Any]							=  False
									a__       :						List[Any]							=  False

									if self.does_advance(__lowercase  ):
												self.current_seq.append(__lowercase  )
												a__       :						Tuple							=  True
									else:
												a__       :						Union[str, Any]							=  True
												self.reset()

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

									return stepped, completed, reset

						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				Any:
									"""simple docstring"""




									a__       :						Tuple							=  False
									a__       :						Optional[int]							=  []

						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				Union[str, Any]:
									"""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 ,       __lowercase=False  ) ->				Optional[int]:
									"""simple docstring"""




									a__       :						str							=  DisjunctiveConstraint(self.token_ids  )

									if stateful:
												a__       :						List[Any]							=  self.seqlen
												a__       :						Optional[Any]							=  self.current_seq
												a__       :						Optional[Any]							=  self.completed

									return new_constraint




class        snake_case__    :







						"""simple docstring"""




						def __init__(       self ,       __lowercase  ) ->				Optional[Any]:
									"""simple docstring"""




									a__       :						List[str]							=  constraints

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

									self.init_state()

						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				int:
									"""simple docstring"""




									a__       :						List[str]							=  []
									a__       :						List[Any]							=  None
									a__       :						Optional[int]							=  [constraint.copy(stateful=__lowercase  ) for constraint in self.constraints]

						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				str:
									"""simple docstring"""




									a__       :						Optional[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 							SCREAMING_SNAKE_CASE__(       self  ) ->				Optional[Any]:
									"""simple docstring"""




									a__       :						Any							=  []
									if self.inprogress_constraint is None:
												for constraint in self.pending_constraints:  # "pending" == "unfulfilled yet"
															a__       :						List[Any]							=  constraint.advance()
															if isinstance(__lowercase ,       __lowercase  ):
																		token_list.append(__lowercase  )
															elif isinstance(__lowercase ,       __lowercase  ):
																		token_list.extend(__lowercase  )
									else:
												a__       :						List[str]							=  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 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase  ) ->				Union[str, Any]:
									"""simple docstring"""




									self.init_state()

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

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

						def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase  ) ->				Any:
									"""simple docstring"""




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

									a__       :						Optional[Any]							=  False, False

									if self.completed:
												a__       :						List[str]							=  True
												a__       :						Tuple							=  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__       :						int							=  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__       :						List[Any]							=  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__       :						int							=  None

															if len(self.pending_constraints  ) == 0:
																		# we're done!
																		a__       :						Optional[Any]							=  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__       :						Optional[Any]							=  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__       :						List[Any]							=  None

																		if not complete and stepped:
																					a__       :						Optional[Any]							=  pending_constraint

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

																					a__       :						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.

																								a__       :						Optional[int]							=  True

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

									return complete, stepped

						def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase=True  ) ->				Optional[Any]:
									"""simple docstring"""




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

									if stateful:
												a__       :						str							=  [
												    constraint.copy(stateful=__lowercase  ) for constraint in self.complete_constraints
												]
												if self.inprogress_constraint is not None:
															a__       :						List[str]							=  self.inprogress_constraint.copy(stateful=__lowercase  )
												a__       :						Optional[int]							=  [constraint.copy() for constraint in self.pending_constraints]

									return new_state









import os
import sys
from contextlib import contextmanager


# Windows only
if os.name == "nt":
		import ctypes
		import msvcrt  # noqa

		class        snake_case__    (ctypes.Structure		):







								"""simple docstring"""




								__lowerCAmelCase					:Dict      =					[("size", ctypes.c_int), ("visible", ctypes.c_byte)]

def      lowerCAmelCase_					(  )							->	List[Any]:







			"""simple docstring"""
			if os.name == "nt":
						a__       :						int							=  CursorInfo()
						a__       :						Union[str, Any]							=  ctypes.windll.kernelaa.GetStdHandle(-11)
						ctypes.windll.kernelaa.GetConsoleCursorInfo(_lowercase						,       ctypes.byref(_lowercase))
						a__       :						List[str]							=  False
						ctypes.windll.kernelaa.SetConsoleCursorInfo(_lowercase						,       ctypes.byref(_lowercase))
			elif os.name == "posix":
						sys.stdout.write("""\033[?25l""")
						sys.stdout.flush()

def      lowerCAmelCase_					(  )							->	Optional[Any]:







			"""simple docstring"""
			if os.name == "nt":
						a__       :						List[Any]							=  CursorInfo()
						a__       :						Optional[int]							=  ctypes.windll.kernelaa.GetStdHandle(-11)
						ctypes.windll.kernelaa.GetConsoleCursorInfo(_lowercase						,       ctypes.byref(_lowercase))
						a__       :						Dict							=  True
						ctypes.windll.kernelaa.SetConsoleCursorInfo(_lowercase						,       ctypes.byref(_lowercase))
			elif os.name == "posix":
						sys.stdout.write("""\033[?25h""")
						sys.stdout.flush()





@contextmanager
def      lowerCAmelCase_					(  )							->	Any:







			"""simple docstring"""
			try:
						hide_cursor()
						yield
			finally:
						show_cursor()




