


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




class A  (   UpperCamelCase_     ):






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




             self.test()






      def        lowerCamelCase       (					self						:     Any )					->						Tuple:
             """simple docstring"""




             _lowerCamelCase       :		str		=0
             _lowerCamelCase       :		Optional[int]		=False
             while not completed:
                    if counter == 1:
                           self.reset()
                    _lowerCamelCase       :		Optional[Any]		=self.advance()
                    if not self.does_advance(lowercase_ ):
                           raise Exception(
                               'Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.' )

                    _lowerCamelCase	,     _lowerCamelCase	,     _lowerCamelCase       :		List[Any]		=self.update(lowercase_ )
                    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        lowerCamelCase       (					self						:     List[Any] )					->						List[str]:
             """simple docstring"""




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






      @abstractmethod
      def        lowerCamelCase       (					self						:     Tuple			,   lowercase_						:     int )					->						int:
             """simple docstring"""




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






      @abstractmethod
      def        lowerCamelCase       (					self						:     List[Any]			,   lowercase_						:     int )					->						str:
             """simple docstring"""




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






      @abstractmethod
      def        lowerCamelCase       (					self						:     Optional[int] )					->						Union[str, Any]:
             """simple docstring"""




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






      @abstractmethod
      def        lowerCamelCase       (					self						:     Union[str, Any] )					->						int:
             """simple docstring"""




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






      @abstractmethod
      def        lowerCamelCase       (					self						:     Union[str, Any]			,   lowercase_						:     List[Any]=False )					->						Union[str, Any]:
             """simple docstring"""




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




class A  (   UpperCamelCase_     ):






      def __init__(					self						:     Any			,   lowercase_						:     List[int] )					->						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}.''' )

             _lowerCamelCase       :		int		=token_ids

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






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




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






      def        lowerCamelCase       (					self						:     Dict			,   lowercase_						:     int )					->						List[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_ )}''' )

             if self.completed:
                    return False

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






      def        lowerCamelCase       (					self						:     Union[str, Any]			,   lowercase_						:     int )					->						List[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_ )}''' )

             _lowerCamelCase       :		Tuple		=False
             _lowerCamelCase       :		Tuple		=False
             _lowerCamelCase       :		Tuple		=False

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






      def        lowerCamelCase       (					self						:     str )					->						int:
             """simple docstring"""




             _lowerCamelCase       :		Any		=False
             _lowerCamelCase       :		Optional[int]		=0






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




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






      def        lowerCamelCase       (					self						:     int			,   lowercase_						:     List[str]=False )					->						Optional[int]:
             """simple docstring"""




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

             if stateful:
                    _lowerCamelCase       :		Any		=self.seqlen
                    _lowerCamelCase       :		int		=self.fulfilled_idx
                    _lowerCamelCase       :		Any		=self.completed

             return new_constraint




class A  :






      def __init__(					self						:     Any			,   lowercase_						:     List[List[int]]			,   lowercase_						:     Tuple=True )					->						Any:
             """simple docstring"""




             _lowerCamelCase       :		Optional[int]		=max([len(lowercase_ ) for one in nested_token_ids] )

             _lowerCamelCase       :		List[str]		={}
             for token_ids in nested_token_ids:
                    _lowerCamelCase       :		int		=root
                    for tidx, token_id in enumerate(lowercase_ ):
                           if token_id not in level:
                                  _lowerCamelCase       :		Tuple		={}

                           _lowerCamelCase       :		List[str]		=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}.''' )

             _lowerCamelCase       :		Union[str, Any]		=root






      def        lowerCamelCase       (					self						:     Optional[int]			,   lowercase_						:     Dict )					->						int:
             """simple docstring"""




             _lowerCamelCase       :		List[Any]		=self.trie

             for current_token in current_seq:
                    _lowerCamelCase       :		int		=start[current_token]

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

             return next_tokens






      def        lowerCamelCase       (					self						:     List[str]			,   lowercase_						:     Optional[Any] )					->						Tuple:
             """simple docstring"""




             _lowerCamelCase       :		Any		=self.next_tokens(lowercase_ )

             return len(lowercase_ ) == 0






      def        lowerCamelCase       (					self						:     Union[str, Any]			,   lowercase_						:     List[str] )					->						Dict:
             """simple docstring"""




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






      def        lowerCamelCase       (					self						:     List[str]			,   lowercase_						:     int			,   lowercase_						:     Union[str, Any] )					->						Optional[int]:
             """simple docstring"""




             _lowerCamelCase       :		Optional[int]		=self.count_leaves(lowercase_ )
             return len(lowercase_ ) != leaf_count




class A  (   UpperCamelCase_     ):






      def __init__(					self						:     List[str]			,   lowercase_						:     List[List[int]] )					->						str:
             """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}.''' )

             _lowerCamelCase       :		Any		=DisjunctiveTrie(lowercase_ )
             _lowerCamelCase       :		Tuple		=nested_token_ids

             _lowerCamelCase       :		Tuple		=self.trie.max_height
             _lowerCamelCase       :		Optional[Any]		=[]
             _lowerCamelCase       :		int		=False






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




             _lowerCamelCase       :		Dict		=self.trie.next_tokens(self.current_seq )

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






      def        lowerCamelCase       (					self						:     Optional[Any]			,   lowercase_						:     int )					->						Any:
             """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_ )}''' )

             _lowerCamelCase       :		int		=self.trie.next_tokens(self.current_seq )

             return token_id in next_tokens






      def        lowerCamelCase       (					self						:     List[str]			,   lowercase_						:     int )					->						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_ )}''' )

             _lowerCamelCase       :		Optional[Any]		=False
             _lowerCamelCase       :		Optional[int]		=False
             _lowerCamelCase       :		Dict		=False

             if self.does_advance(lowercase_ ):
                    self.current_seq.append(lowercase_ )
                    _lowerCamelCase       :		List[Any]		=True
             else:
                    _lowerCamelCase       :		List[str]		=True
                    self.reset()

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

             return stepped, completed, reset






      def        lowerCamelCase       (					self						:     Optional[Any] )					->						List[str]:
             """simple docstring"""




             _lowerCamelCase       :		List[Any]		=False
             _lowerCamelCase       :		List[Any]		=[]






      def        lowerCamelCase       (					self						:     Dict )					->						List[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        lowerCamelCase       (					self						:     str			,   lowercase_						:     Any=False )					->						Dict:
             """simple docstring"""




             _lowerCamelCase       :		List[str]		=DisjunctiveConstraint(self.token_ids )

             if stateful:
                    _lowerCamelCase       :		Any		=self.seqlen
                    _lowerCamelCase       :		List[str]		=self.current_seq
                    _lowerCamelCase       :		List[str]		=self.completed

             return new_constraint




class A  :






      def __init__(					self						:     List[str]			,   lowercase_						:     List[Constraint] )					->						Dict:
             """simple docstring"""




             _lowerCamelCase       :		Optional[int]		=constraints

             # max # of steps required to fulfill a given constraint
             _lowerCamelCase       :		Optional[Any]		=max([c.seqlen for c in constraints] )
             _lowerCamelCase       :		Any		=len(lowercase_ )
             _lowerCamelCase       :		List[Any]		=False

             self.init_state()






      def        lowerCamelCase       (					self						:     Dict )					->						int:
             """simple docstring"""




             _lowerCamelCase       :		Dict		=[]
             _lowerCamelCase       :		int		=None
             _lowerCamelCase       :		Optional[Any]		=[constraint.copy(stateful=lowercase_ ) for constraint in self.constraints]






      def        lowerCamelCase       (					self						:     Dict )					->						str:
             """simple docstring"""




             _lowerCamelCase       :		Dict		=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        lowerCamelCase       (					self						:     Dict )					->						Optional[Any]:
             """simple docstring"""




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




             self.init_state()

             if token_ids is not None:
                    for token in token_ids:
                           # completes or steps **one** constraint
                           _lowerCamelCase	,     _lowerCamelCase       :		List[Any]		=self.add(lowercase_ )

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






      def        lowerCamelCase       (					self						:     List[Any]			,   lowercase_						:     int )					->						Optional[Any]:
             """simple docstring"""




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

             _lowerCamelCase	,     _lowerCamelCase       :		Tuple		=False, False

             if self.completed:
                    _lowerCamelCase       :		Optional[int]		=True
                    _lowerCamelCase       :		Union[str, 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	,     _lowerCamelCase	,     _lowerCamelCase       :		Tuple		=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_ ) )
                           _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       :		Dict		=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(lowercase_ ):
                                  _lowerCamelCase	,     _lowerCamelCase	,     _lowerCamelCase       :		List[str]		=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_ )
                                         _lowerCamelCase       :		Any		=None

                                  if not complete and stepped:
                                         _lowerCamelCase       :		str		=pending_constraint

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

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

                                                _lowerCamelCase       :		Dict		=True

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

             return complete, stepped






      def        lowerCamelCase       (					self						:     List[str]			,   lowercase_						:     Union[str, Any]=True )					->						Optional[int]:
             """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       :		Dict		=[
                        constraint.copy(stateful=lowercase_ ) for constraint in self.complete_constraints
                    ]
                    if self.inprogress_constraint is not None:
                           _lowerCamelCase       :		Optional[int]		=self.inprogress_constraint.copy(stateful=lowercase_ )
                    _lowerCamelCase       :		str		=[constraint.copy() for constraint in self.pending_constraints]

             return new_state






import sys

from .dependency_versions_table import deps
from .utils.versions import require_version, require_version_core


# define which module versions we always want to check at run time
# (usually the ones defined in `install_requires` in setup.py)
#
# order specific notes:
# - tqdm must be checked before tokenizers

lowerCamelCase											=       'python tqdm regex requests packaging filelock numpy tokenizers'.split()
if sys.version_info < (3, 7):
 pkgs_to_check_at_runtime.append('dataclasses')
if sys.version_info < (3, 8):
 pkgs_to_check_at_runtime.append('importlib_metadata')

for pkg in pkgs_to_check_at_runtime:
 if pkg in deps:
  if pkg == "tokenizers":
   # must be loaded here, or else tqdm check may fail
   from .utils import is_tokenizers_available

   if not is_tokenizers_available():
    continue  # not required, check version only if installed

  require_version_core(deps[pkg])
 else:
  raise ValueError(F"""can't find {pkg} in {deps.keys()}, check dependency_versions_table.py""")




def 	a_      (    SCREAMING_SNAKE_CASE__					:      int		,			SCREAMING_SNAKE_CASE__					:      str=None     ):
       '''simple docstring'''





       require_version(deps[pkg]		,			SCREAMING_SNAKE_CASE__     )


