



"""simple docstring"""







import copy
import tempfile
import unittest

from huggingface_hub import HfFolder, delete_repo
from parameterized import parameterized
from requests.exceptions import HTTPError

from transformers import AutoConfig, GenerationConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test







class 				UpperCamelCase__       (     unittest.TestCase  ):




						"""simple docstring"""




						@parameterized.expand([(None,), ('foo.json',)]	)
						def 					SCREAMING_SNAKE_CASE__			(				self    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				Dict	):
								lowerCAmelCase_       :    str								=			GenerationConfig(
								    do_sample=SCREAMING_SNAKE_CASE_   ,      temperature=0.7   ,      length_penalty=1.0   ,      bad_words_ids=[[1, 2, 3], [4, 5]]   ,      )
								with tempfile.TemporaryDirectory() as tmp_dir:
										config.save_pretrained(SCREAMING_SNAKE_CASE_   ,      config_name=SCREAMING_SNAKE_CASE_	)
										lowerCAmelCase_       :    List[str]								=			GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_   ,      config_name=SCREAMING_SNAKE_CASE_	)

								# Checks parameters that were specified
								self.assertEqual(loaded_config.do_sample   ,      SCREAMING_SNAKE_CASE_	)
								self.assertEqual(loaded_config.temperature   ,      0.7	)
								self.assertEqual(loaded_config.length_penalty   ,      1.0	)
								self.assertEqual(loaded_config.bad_words_ids   ,      [[1, 2, 3], [4, 5]]	)

								# Checks parameters that were not specified (defaults)
								self.assertEqual(loaded_config.top_k   ,      5_0	)
								self.assertEqual(loaded_config.max_length   ,      2_0	)
								self.assertEqual(loaded_config.max_time   ,      SCREAMING_SNAKE_CASE_	)



						def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]	):
								lowerCAmelCase_       :    List[str]								=			AutoConfig.from_pretrained('gpt2'	)
								lowerCAmelCase_       :    Tuple								=			GenerationConfig.from_model_config(SCREAMING_SNAKE_CASE_	)
								lowerCAmelCase_       :    Optional[int]								=			GenerationConfig()

								# The generation config has loaded a few non-default parameters from the model config
								self.assertNotEqual(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	)

								# One of those parameters is eos_token_id -- check if it matches
								self.assertNotEqual(generation_config_from_model.eos_token_id   ,      default_generation_config.eos_token_id	)
								self.assertEqual(generation_config_from_model.eos_token_id   ,      model_config.eos_token_id	)



						def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]	):
								lowerCAmelCase_       :    Optional[int]								=			GenerationConfig()
								lowerCAmelCase_       :    str								=			{
								    'max_new_tokens': 1_0_2_4,
								    'foo': 'bar',
								}
								lowerCAmelCase_       :    List[str]								=			copy.deepcopy(SCREAMING_SNAKE_CASE_	)
								lowerCAmelCase_       :    Optional[Any]								=			generation_config.update(**SCREAMING_SNAKE_CASE_	)

								# update_kwargs was not modified (no side effects)
								self.assertEqual(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	)

								# update_kwargs was used to update the config on valid attributes
								self.assertEqual(generation_config.max_new_tokens   ,      1_0_2_4	)

								# `.update()` returns a dictionary of unused kwargs
								self.assertEqual(SCREAMING_SNAKE_CASE_   ,      {'foo': 'bar'}	)



						def 					SCREAMING_SNAKE_CASE__			(				self    :				List[Any]	):
								lowerCAmelCase_       :    List[str]								=			GenerationConfig()
								lowerCAmelCase_       :    Tuple								=			'bar'

								with tempfile.TemporaryDirectory('test-generation-config'	) as tmp_dir:
										generation_config.save_pretrained(SCREAMING_SNAKE_CASE_	)

										lowerCAmelCase_       :    Optional[int]								=			GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_	)
								# update_kwargs was used to update the config on valid attributes
								self.assertEqual(new_config.foo   ,      'bar'	)

								lowerCAmelCase_       :    Tuple								=			GenerationConfig.from_model_config(SCREAMING_SNAKE_CASE_	)
								assert not hasattr(SCREAMING_SNAKE_CASE_   ,      'foo'	)  # no new kwargs should be initialized if from config





						def 					SCREAMING_SNAKE_CASE__			(				self    :				Dict	):
								lowerCAmelCase_       :    Any								=			GenerationConfig()
								self.assertEqual(default_config.temperature   ,      1.0	)
								self.assertEqual(default_config.do_sample   ,      SCREAMING_SNAKE_CASE_	)
								self.assertEqual(default_config.num_beams   ,      1	)

								lowerCAmelCase_       :    str								=			GenerationConfig(
								    do_sample=SCREAMING_SNAKE_CASE_   ,      temperature=0.7   ,      length_penalty=1.0   ,      bad_words_ids=[[1, 2, 3], [4, 5]]   ,      )
								self.assertEqual(config.temperature   ,      0.7	)
								self.assertEqual(config.do_sample   ,      SCREAMING_SNAKE_CASE_	)
								self.assertEqual(config.num_beams   ,      1	)

								with tempfile.TemporaryDirectory() as tmp_dir:
										config.save_pretrained(SCREAMING_SNAKE_CASE_	)
										lowerCAmelCase_       :    int								=			GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_   ,      temperature=1.0	)

								self.assertEqual(loaded_config.temperature   ,      1.0	)
								self.assertEqual(loaded_config.do_sample   ,      SCREAMING_SNAKE_CASE_	)
								self.assertEqual(loaded_config.num_beams   ,      1	)  # default value







@is_staging_test
class 				UpperCamelCase__       (     unittest.TestCase  ):




						"""simple docstring"""




						@classmethod
						def 					SCREAMING_SNAKE_CASE__			(				cls    :				int	):
								lowerCAmelCase_       :    Optional[Any]								=			TOKEN
								HfFolder.save_token(SCREAMING_SNAKE_CASE_	)



						@classmethod
						def 					SCREAMING_SNAKE_CASE__			(				cls    :				str	):
								try:
										delete_repo(token=cls._token   ,      repo_id='test-generation-config'	)
								except HTTPError:
										pass

								try:
										delete_repo(token=cls._token   ,      repo_id='valid_org/test-generation-config-org'	)
								except HTTPError:
										pass



						def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[int]	):
								lowerCAmelCase_       :    int								=			GenerationConfig(
								    do_sample=SCREAMING_SNAKE_CASE_   ,      temperature=0.7   ,      length_penalty=1.0   ,      )
								config.push_to_hub('test-generation-config'   ,      use_auth_token=self._token	)

								lowerCAmelCase_       :    Optional[Any]								=			GenerationConfig.from_pretrained(F"{USER}/test-generation-config"	)
								for k, v in config.to_dict().items():
										if k != "transformers_version":
												self.assertEqual(SCREAMING_SNAKE_CASE_   ,      getattr(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	)	)

        # Reset repo
								delete_repo(token=self._token   ,      repo_id='test-generation-config'	)

								# Push to hub via save_pretrained
								with tempfile.TemporaryDirectory() as tmp_dir:
										config.save_pretrained(
										    SCREAMING_SNAKE_CASE_   ,      repo_id='test-generation-config'   ,      push_to_hub=SCREAMING_SNAKE_CASE_   ,      use_auth_token=self._token	)

								lowerCAmelCase_       :    Optional[Any]								=			GenerationConfig.from_pretrained(F"{USER}/test-generation-config"	)
								for k, v in config.to_dict().items():
										if k != "transformers_version":
												self.assertEqual(SCREAMING_SNAKE_CASE_   ,      getattr(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	)	)





						def 					SCREAMING_SNAKE_CASE__			(				self    :				Union[str, Any]	):
								lowerCAmelCase_       :    Optional[Any]								=			GenerationConfig(
								    do_sample=SCREAMING_SNAKE_CASE_   ,      temperature=0.7   ,      length_penalty=1.0   ,      )
								config.push_to_hub('valid_org/test-generation-config-org'   ,      use_auth_token=self._token	)

								lowerCAmelCase_       :    Union[str, Any]								=			GenerationConfig.from_pretrained('valid_org/test-generation-config-org'	)
								for k, v in config.to_dict().items():
										if k != "transformers_version":
												self.assertEqual(SCREAMING_SNAKE_CASE_   ,      getattr(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	)	)

        # Reset repo
								delete_repo(token=self._token   ,      repo_id='valid_org/test-generation-config-org'	)

								# Push to hub via save_pretrained
								with tempfile.TemporaryDirectory() as tmp_dir:
										config.save_pretrained(
										    SCREAMING_SNAKE_CASE_   ,      repo_id='valid_org/test-generation-config-org'   ,      push_to_hub=SCREAMING_SNAKE_CASE_   ,      use_auth_token=self._token	)

								lowerCAmelCase_       :    Union[str, Any]								=			GenerationConfig.from_pretrained('valid_org/test-generation-config-org'	)
								for k, v in config.to_dict().items():
										if k != "transformers_version":
												self.assertEqual(SCREAMING_SNAKE_CASE_   ,      getattr(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	)	)










"""simple docstring"""







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







class 				UpperCamelCase__       (     lowercase_  ):




      """simple docstring"""




      def __init__(				self    :				int	):
        # test for the above condition
        self.test()



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

          lowerCAmelCase_						,lowerCAmelCase_						,lowerCAmelCase_       :    List[str]								=			self.update(SCREAMING_SNAKE_CASE_	)
          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    :				Tuple	):
        raise NotImplementedError(
            F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."	)



      @abstractmethod
      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[Any]   ,      SCREAMING_SNAKE_CASE_    :				int	):
        raise NotImplementedError(
            F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."	)



      @abstractmethod
      def 					SCREAMING_SNAKE_CASE__			(				self    :				int   ,      SCREAMING_SNAKE_CASE_    :				int	):
        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]	):
        raise NotImplementedError(
            F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."	)



      @abstractmethod
      def 					SCREAMING_SNAKE_CASE__			(				self    :				str	):
        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]   ,      SCREAMING_SNAKE_CASE_    :				Optional[int]=False	):
        raise NotImplementedError(
            F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."	)







class 				UpperCamelCase__       (     lowercase_  ):




      """simple docstring"""




      def __init__(				self    :				Tuple   ,      SCREAMING_SNAKE_CASE_    :				List[int]	):
        super(SCREAMING_SNAKE_CASE_   ,      self	).__init__()

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

        lowerCAmelCase_       :    Union[str, Any]								=			len(self.token_ids	)
        lowerCAmelCase_       :    Union[str, Any]								=			-1  # the index of the currently fulfilled step
        lowerCAmelCase_       :    Dict								=			False



      def 					SCREAMING_SNAKE_CASE__			(				self    :				int	):
        if self.completed:
          return None
        return self.token_ids[self.fulfilled_idx + 1]



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

        if self.completed:
          return False

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



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Union[str, Any]   ,      SCREAMING_SNAKE_CASE_    :				int	):
        if not isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	):
          raise ValueError(F"`token_id` has to be an `int`, but is {token_id} of type {type(SCREAMING_SNAKE_CASE_	)}"	)

        lowerCAmelCase_       :    List[Any]								=			False
        lowerCAmelCase_       :    Optional[int]								=			False
        lowerCAmelCase_       :    Union[str, Any]								=			False

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



      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[Any]	):
        lowerCAmelCase_       :    Optional[int]								=			False
        lowerCAmelCase_       :    int								=			0



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Tuple	):
        return self.seqlen - (self.fulfilled_idx + 1)





      def 					SCREAMING_SNAKE_CASE__			(				self    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				Tuple=False	):
        lowerCAmelCase_       :    Any								=			PhrasalConstraint(self.token_ids	)

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

        return new_constraint







class 				UpperCamelCase__       :




      """simple docstring"""




      def __init__(				self    :				List[Any]   ,      SCREAMING_SNAKE_CASE_    :				List[List[int]]   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]=True	):
        lowerCAmelCase_       :    Tuple								=			max([len(SCREAMING_SNAKE_CASE_	) for one in nested_token_ids]	)

        lowerCAmelCase_       :    Optional[Any]								=			{}
        for token_ids in nested_token_ids:
          lowerCAmelCase_       :    Union[str, Any]								=			root
          for tidx, token_id in enumerate(SCREAMING_SNAKE_CASE_	):
            if token_id not in level:
              lowerCAmelCase_       :    Dict								=			{}

            lowerCAmelCase_       :    Tuple								=			level[token_id]

        if no_subsets and self.has_subsets(SCREAMING_SNAKE_CASE_   ,      SCREAMING_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_       :    Union[str, Any]								=			root



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				Any	):
        lowerCAmelCase_       :    str								=			self.trie

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

        lowerCAmelCase_       :    Dict								=			list(start.keys()	)

        return next_tokens



      def 					SCREAMING_SNAKE_CASE__			(				self    :				str   ,      SCREAMING_SNAKE_CASE_    :				Any	):
        lowerCAmelCase_       :    Any								=			self.next_tokens(SCREAMING_SNAKE_CASE_	)

        return len(SCREAMING_SNAKE_CASE_	) == 0



      def 					SCREAMING_SNAKE_CASE__			(				self    :				int   ,      SCREAMING_SNAKE_CASE_    :				int	):
        lowerCAmelCase_       :    Tuple								=			list(root.values()	)
        if len(SCREAMING_SNAKE_CASE_	) == 0:
          return 1
        else:
          return sum([self.count_leaves(SCREAMING_SNAKE_CASE_	) for nn in next_nodes]	)





      def 					SCREAMING_SNAKE_CASE__			(				self    :				Union[str, Any]   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]	):
        lowerCAmelCase_       :    Any								=			self.count_leaves(SCREAMING_SNAKE_CASE_	)
        return len(SCREAMING_SNAKE_CASE_	) != leaf_count







class 				UpperCamelCase__       (     lowercase_  ):




      """simple docstring"""




      def __init__(				self    :				List[Any]   ,      SCREAMING_SNAKE_CASE_    :				List[List[int]]	):
        super(SCREAMING_SNAKE_CASE_   ,      self	).__init__()

        if not isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	) or len(SCREAMING_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(SCREAMING_SNAKE_CASE_   ,      SCREAMING_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(SCREAMING_SNAKE_CASE_   ,      SCREAMING_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(SCREAMING_SNAKE_CASE_	)
        lowerCAmelCase_       :    Optional[int]								=			nested_token_ids

        lowerCAmelCase_       :    Tuple								=			self.trie.max_height
        lowerCAmelCase_       :    Union[str, Any]								=			[]
        lowerCAmelCase_       :    Optional[Any]								=			False



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Dict	):
        lowerCAmelCase_       :    int								=			self.trie.next_tokens(self.current_seq	)

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



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				int	):
        if not isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	):
          raise ValueError(F"`token_id` is supposed to be type `int`, but is {token_id} of type {type(SCREAMING_SNAKE_CASE_	)}"	)

        lowerCAmelCase_       :    Optional[int]								=			self.trie.next_tokens(self.current_seq	)

        return token_id in next_tokens



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Any   ,      SCREAMING_SNAKE_CASE_    :				int	):
        if not isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	):
          raise ValueError(F"`token_id` is supposed to be type `int`, but is {token_id} of type {type(SCREAMING_SNAKE_CASE_	)}"	)

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

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

        lowerCAmelCase_       :    Dict								=			self.trie.reached_leaf(self.current_seq	)
        lowerCAmelCase_       :    List[str]								=			completed

        return stepped, completed, reset



      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[Any]	):
        lowerCAmelCase_       :    int								=			False
        lowerCAmelCase_       :    Optional[Any]								=			[]



      def 					SCREAMING_SNAKE_CASE__			(				self    :				str	):
        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    :				Tuple   ,      SCREAMING_SNAKE_CASE_    :				Dict=False	):
        lowerCAmelCase_       :    Dict								=			DisjunctiveConstraint(self.token_ids	)

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

        return new_constraint







class 				UpperCamelCase__       :




      """simple docstring"""




      def __init__(				self    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				List[Constraint]	):
        lowerCAmelCase_       :    Optional[int]								=			constraints

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

        self.init_state()



      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[Any]	):
        lowerCAmelCase_       :    Tuple								=			[]
        lowerCAmelCase_       :    int								=			None
        lowerCAmelCase_       :    Optional[int]								=			[constraint.copy(stateful=SCREAMING_SNAKE_CASE_	) for constraint in self.constraints]



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

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



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				Optional[List[int]]	):
        self.init_state()

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

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



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				int	):
        if not isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	):
          raise ValueError(F"`token_id` should be an `int`, but is `{token_id}`."	)

        lowerCAmelCase_						,lowerCAmelCase_       :    Tuple								=			False, False

        if self.completed:
          lowerCAmelCase_       :    Any								=			True
          lowerCAmelCase_       :    Dict								=			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_       :    Any								=			self.inprogress_constraint.update(SCREAMING_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=SCREAMING_SNAKE_CASE_	)	)
            lowerCAmelCase_       :    Optional[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_       :    str								=			None

            if len(self.pending_constraints	) == 0:
              # we're done!
              lowerCAmelCase_       :    Union[str, 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(SCREAMING_SNAKE_CASE_	):
              lowerCAmelCase_						,lowerCAmelCase_						,lowerCAmelCase_       :    str								=			pending_constraint.update(SCREAMING_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(SCREAMING_SNAKE_CASE_	)
                lowerCAmelCase_       :    Any								=			None

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

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

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

                  lowerCAmelCase_       :    Optional[Any]								=			True

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

        return complete, stepped





      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				str=True	):
        lowerCAmelCase_       :    List[Any]								=			ConstraintListState(self.constraints	)  # we actually never though self.constraints objects
        # throughout this process. So it's at initialization state.

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

        return new_state





