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




class    _UpperCamelCase      (						_UpperCAmelCase ):


			"""simple docstring"""






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

							'''simple docstring'''


							self.test()





			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					List[str]:

							'''simple docstring'''


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

											__lowercase			,     __lowercase			,     __lowercase 			=							self.update(lowerCAmelCase__						)
											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        _SCREAMING_SNAKE_CASE			(   self						)     ->					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      ,   lowerCAmelCase__						)     ->					List[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      ,   lowerCAmelCase__						)     ->					Union[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						)     ->					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						)     ->					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      ,   lowerCAmelCase__=False						)     ->					Optional[int]:

							'''simple docstring'''


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




class    _UpperCamelCase      (						_UpperCAmelCase ):


			"""simple docstring"""






			def __init__(   self      ,   lowerCAmelCase__						)     ->					Dict:

							'''simple docstring'''


							super(lowerCAmelCase__      ,   self						).__init__()

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

							'''simple docstring'''


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





			def        _SCREAMING_SNAKE_CASE			(   self      ,   lowerCAmelCase__						)     ->					str:

							'''simple docstring'''


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

							if self.completed:
											return False

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





			def        _SCREAMING_SNAKE_CASE			(   self      ,   lowerCAmelCase__						)     ->					Dict:

							'''simple docstring'''


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

							__lowercase 			=							False
							__lowercase 			=							False
							__lowercase 			=							False

							if self.does_advance(lowerCAmelCase__						):
											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						)     ->					Union[str, Any]:

							'''simple docstring'''


							__lowercase 			=							False
							__lowercase 			=							0





			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					int:

							'''simple docstring'''


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





			def        _SCREAMING_SNAKE_CASE			(   self      ,   lowerCAmelCase__=False						)     ->					List[str]:

							'''simple docstring'''


							__lowercase 			=							PhrasalConstraint(self.token_ids						)

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

							return new_constraint




class    _UpperCamelCase      :


			"""simple docstring"""






			def __init__(   self      ,   lowerCAmelCase__      ,   lowerCAmelCase__=True						)     ->					Dict:

							'''simple docstring'''


							__lowercase 			=							max([len(lowerCAmelCase__						) for one in nested_token_ids]						)

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

															__lowercase 			=							level[token_id]

							if no_subsets and self.has_subsets(lowerCAmelCase__      ,   lowerCAmelCase__						):
											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      ,   lowerCAmelCase__						)     ->					Optional[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      ,   lowerCAmelCase__						)     ->					List[Any]:

							'''simple docstring'''


							__lowercase 			=							self.next_tokens(lowerCAmelCase__						)

							return len(lowerCAmelCase__						) == 0





			def        _SCREAMING_SNAKE_CASE			(   self      ,   lowerCAmelCase__						)     ->					List[Any]:

							'''simple docstring'''


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





			def        _SCREAMING_SNAKE_CASE			(   self      ,   lowerCAmelCase__      ,   lowerCAmelCase__						)     ->					List[Any]:

							'''simple docstring'''


							__lowercase 			=							self.count_leaves(lowerCAmelCase__						)
							return len(lowerCAmelCase__						) != leaf_count




class    _UpperCamelCase      (						_UpperCAmelCase ):


			"""simple docstring"""






			def __init__(   self      ,   lowerCAmelCase__						)     ->					str:

							'''simple docstring'''


							super(lowerCAmelCase__      ,   self						).__init__()

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

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





			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					Dict:

							'''simple docstring'''


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

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





			def        _SCREAMING_SNAKE_CASE			(   self      ,   lowerCAmelCase__						)     ->					Any:

							'''simple docstring'''


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

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

							return token_id in next_tokens





			def        _SCREAMING_SNAKE_CASE			(   self      ,   lowerCAmelCase__						)     ->					Union[str, Any]:

							'''simple docstring'''


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

							__lowercase 			=							False
							__lowercase 			=							False
							__lowercase 			=							False

							if self.does_advance(lowerCAmelCase__						):
											self.current_seq.append(lowerCAmelCase__						)
											__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						)     ->					Tuple:

							'''simple docstring'''


							__lowercase 			=							False
							__lowercase 			=							[]





			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					List[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      ,   lowerCAmelCase__=False						)     ->					Optional[int]:

							'''simple docstring'''


							__lowercase 			=							DisjunctiveConstraint(self.token_ids						)

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

							return new_constraint




class    _UpperCamelCase      :


			"""simple docstring"""






			def __init__(   self      ,   lowerCAmelCase__						)     ->					str:

							'''simple docstring'''


							__lowercase 			=							constraints

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

							self.init_state()





			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					List[str]:

							'''simple docstring'''


							__lowercase 			=							[]
							__lowercase 			=							None
							__lowercase 			=							[constraint.copy(stateful=lowerCAmelCase__						) for constraint in self.constraints]





			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					int:

							'''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						)     ->					Dict:

							'''simple docstring'''


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

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





			def        _SCREAMING_SNAKE_CASE			(   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 			=							self.add(lowerCAmelCase__						)

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





			def        _SCREAMING_SNAKE_CASE			(   self      ,   lowerCAmelCase__						)     ->					int:

							'''simple docstring'''


							if not isinstance(lowerCAmelCase__      ,   lowerCAmelCase__						):
											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(lowerCAmelCase__						)
											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=lowerCAmelCase__						)						)
															__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(lowerCAmelCase__						):
																			__lowercase			,     __lowercase			,     __lowercase 			=							pending_constraint.update(lowerCAmelCase__						)

																			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(lowerCAmelCase__						)
																							__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      ,   lowerCAmelCase__=True						)     ->					List[Any]:

							'''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=lowerCAmelCase__						) for constraint in self.complete_constraints
											]
											if self.inprogress_constraint is not None:
															__lowercase 			=							self.inprogress_constraint.copy(stateful=lowerCAmelCase__						)
											__lowercase 			=							[constraint.copy() for constraint in self.pending_constraints]

							return new_state
import warnings
from functools import wraps
from typing import Callable





def 				UpperCAmelCase						(    lowercase							):







				"""simple docstring"""



				@wraps(lowercase							)
				def _inner_fn(*lowercase							,			**lowercase							):
								warnings.warn(
								    (F"'{fn.__name__}' is experimental and might be subject to breaking changes in the future.")							,			lowercase							,			)
								return fn(*lowercase							,			**lowercase							)

				return _inner_fn