






from __future__ import annotations

import unittest

from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available
from transformers.testing_utils import require_tf, require_tokenizers, slow
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
		import tensorflow as tf

		from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel


@require_tf
class 							__a							:





		'''simple docstring'''



		UpperCAmelCase__      :				List[Any]				    =						BlenderbotSmallConfig
		UpperCAmelCase__      :				List[Any]				    =						{}
		UpperCAmelCase__      :				Optional[int]				    =						"""gelu"""


		def __init__(						self ,    UpperCamelCase__ ,    UpperCamelCase__=13 ,    UpperCamelCase__=7 ,    UpperCamelCase__=True ,    UpperCamelCase__=False ,    UpperCamelCase__=99 ,    UpperCamelCase__=32 ,    UpperCamelCase__=2 ,    UpperCamelCase__=4 ,    UpperCamelCase__=37 ,    UpperCamelCase__=0.1 ,    UpperCamelCase__=0.1 ,    UpperCamelCase__=20 ,    UpperCamelCase__=2 ,    UpperCamelCase__=1 ,    UpperCamelCase__=0 ,    ):
						SCREAMING_SNAKE_CASE_   :	int													=   parent
						SCREAMING_SNAKE_CASE_   :	List[str]													=   batch_size
						SCREAMING_SNAKE_CASE_   :	Optional[int]													=   seq_length
						SCREAMING_SNAKE_CASE_   :	Tuple													=   is_training
						SCREAMING_SNAKE_CASE_   :	List[str]													=   use_labels
						SCREAMING_SNAKE_CASE_   :	List[Any]													=   vocab_size
						SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   hidden_size
						SCREAMING_SNAKE_CASE_   :	Optional[int]													=   num_hidden_layers
						SCREAMING_SNAKE_CASE_   :	Optional[int]													=   num_attention_heads
						SCREAMING_SNAKE_CASE_   :	Dict													=   intermediate_size

						SCREAMING_SNAKE_CASE_   :	List[str]													=   hidden_dropout_prob
						SCREAMING_SNAKE_CASE_   :	List[Any]													=   attention_probs_dropout_prob
						SCREAMING_SNAKE_CASE_   :	Optional[int]													=   max_position_embeddings
						SCREAMING_SNAKE_CASE_   :	List[Any]													=   eos_token_id
						SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   pad_token_id
						SCREAMING_SNAKE_CASE_   :	Tuple													=   bos_token_id


		def   __snake_case			(						self       ):
						SCREAMING_SNAKE_CASE_   :	Dict													=   ids_tensor([self.batch_size, self.seq_length - 1] ,    self.vocab_size       )
						SCREAMING_SNAKE_CASE_   :	List[Any]													=   tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size       ) ,    1       )
						SCREAMING_SNAKE_CASE_   :	Optional[int]													=   tf.concat([input_ids, eos_tensor] ,    axis=1       )

						SCREAMING_SNAKE_CASE_   :	Tuple													=   ids_tensor([self.batch_size, self.seq_length] ,    self.vocab_size       )

						SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   self.config_cls(
						    vocab_size=self.vocab_size ,    d_model=self.hidden_size ,    encoder_layers=self.num_hidden_layers ,    decoder_layers=self.num_hidden_layers ,    encoder_attention_heads=self.num_attention_heads ,    decoder_attention_heads=self.num_attention_heads ,    encoder_ffn_dim=self.intermediate_size ,    decoder_ffn_dim=self.intermediate_size ,    dropout=self.hidden_dropout_prob ,    attention_dropout=self.attention_probs_dropout_prob ,    max_position_embeddings=self.max_position_embeddings ,    eos_token_ids=[2] ,    bos_token_id=self.bos_token_id ,    pad_token_id=self.pad_token_id ,    decoder_start_token_id=self.pad_token_id ,    **self.config_updates ,    )
						SCREAMING_SNAKE_CASE_   :	Dict													=   prepare_blenderbot_small_inputs_dict(UpperCAmelCase__ ,    UpperCAmelCase__ ,    UpperCAmelCase__       )
						return config, inputs_dict






		def   __snake_case			(						self ,    UpperCamelCase__ ,    UpperCamelCase__       ):
						SCREAMING_SNAKE_CASE_   :	List[Any]													=   TFBlenderbotSmallModel(config=UpperCAmelCase__       ).get_decoder()
						SCREAMING_SNAKE_CASE_   :	str													=   inputs_dict['''input_ids''']

						SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   input_ids[:1, :]
						SCREAMING_SNAKE_CASE_   :	List[str]													=   inputs_dict['''attention_mask'''][:1, :]
						SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   inputs_dict['''head_mask''']
						SCREAMING_SNAKE_CASE_   :	int													=   1

						# first forward pass
						SCREAMING_SNAKE_CASE_   :	Any													=   model(UpperCAmelCase__ ,    attention_mask=UpperCAmelCase__ ,    head_mask=UpperCAmelCase__ ,    use_cache=UpperCAmelCase__       )

						SCREAMING_SNAKE_CASE_   :	Optional[int]													=   outputs.to_tuple()

						# create hypothetical next token and extent to next_input_ids
						SCREAMING_SNAKE_CASE_   :	int													=   ids_tensor((self.batch_size, 3) ,    config.vocab_size       )
						SCREAMING_SNAKE_CASE_   :	int													=   tf.cast(ids_tensor((self.batch_size, 3) ,    2       ) ,    tf.inta       )

						# append to next input_ids and
						SCREAMING_SNAKE_CASE_   :	int													=   tf.concat([input_ids, next_tokens] ,    axis=-1       )
						SCREAMING_SNAKE_CASE_   :	int													=   tf.concat([attention_mask, next_attn_mask] ,    axis=-1       )

						SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   model(UpperCAmelCase__ ,    attention_mask=UpperCAmelCase__       )[0]
						SCREAMING_SNAKE_CASE_   :	str													=   model(UpperCAmelCase__ ,    attention_mask=UpperCAmelCase__ ,    past_key_values=UpperCAmelCase__       )[0]

						self.parent.assertEqual(next_tokens.shape[1] ,    output_from_past.shape[1]       )

						# select random slice
						SCREAMING_SNAKE_CASE_   :	Any													=   int(ids_tensor((1,) ,    output_from_past.shape[-1]       )       )
						SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   output_from_no_past[:, -3:, random_slice_idx]
						SCREAMING_SNAKE_CASE_   :	List[str]													=   output_from_past[:, :, random_slice_idx]

						# test that outputs are equal for slice
						tf.debugging.assert_near(UpperCAmelCase__ ,    UpperCAmelCase__ ,    rtol=1E-3       )






def 					_lowerCamelCase(			lowerCAmelCase__				:		List[str]    ,    lowerCAmelCase__				:		Optional[Any]    ,    lowerCAmelCase__				:		str    ,    lowerCAmelCase__				:		Optional[int]=None    ,    lowerCAmelCase__				:		Tuple=None    ,    lowerCAmelCase__				:		int=None    ,    lowerCAmelCase__				:		Any=None    ,    lowerCAmelCase__				:		List[Any]=None    ,    ):





				'''simple docstring'''







				if attention_mask is None:
								SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   tf.cast(tf.math.not_equal(lowerCAmelCase__    ,    config.pad_token_id      )    ,    tf.inta      )
				if decoder_attention_mask is None:
								SCREAMING_SNAKE_CASE_   :	Any													=   tf.concat(
								    [
								        tf.ones(decoder_input_ids[:, :1].shape    ,    dtype=tf.inta      ),
								        tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:]    ,    config.pad_token_id      )    ,    tf.inta      ),
								    ]    ,    axis=-1    ,    )
				if head_mask is None:
								SCREAMING_SNAKE_CASE_   :	Dict													=   tf.ones((config.encoder_layers, config.encoder_attention_heads)      )
				if decoder_head_mask is None:
								SCREAMING_SNAKE_CASE_   :	int													=   tf.ones((config.decoder_layers, config.decoder_attention_heads)      )
				if cross_attn_head_mask is None:
								SCREAMING_SNAKE_CASE_   :	Dict													=   tf.ones((config.decoder_layers, config.decoder_attention_heads)      )
				return {
				    "input_ids": input_ids,
				    "decoder_input_ids": decoder_input_ids,
				    "attention_mask": attention_mask,
				    "decoder_attention_mask": decoder_attention_mask,
				    "head_mask": head_mask,
				    "decoder_head_mask": decoder_head_mask,
				    "cross_attn_head_mask": cross_attn_head_mask,
				}


@require_tf
class 							__a							(  lowercase__ ,	lowercase__ ,	unittest.TestCase						):





		'''simple docstring'''



		UpperCAmelCase__      :				Optional[Any]				    =						(
		    (TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else ()
		)
		UpperCAmelCase__      :				Dict				    =						(TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else ()
		UpperCAmelCase__      :				Tuple				    =						(
		    {
		        """conversational""": TFBlenderbotSmallForConditionalGeneration,
		        """feature-extraction""": TFBlenderbotSmallModel,
		        """summarization""": TFBlenderbotSmallForConditionalGeneration,
		        """text2text-generation""": TFBlenderbotSmallForConditionalGeneration,
		        """translation""": TFBlenderbotSmallForConditionalGeneration,
		    }
		    if is_tf_available()
		    else {}
		)
		UpperCAmelCase__      :				Any				    =						True
		UpperCAmelCase__      :				List[Any]				    =						False
		UpperCAmelCase__      :				Optional[Any]				    =						False


		def   __snake_case			(						self       ):
						SCREAMING_SNAKE_CASE_   :	Tuple													=   TFBlenderbotSmallModelTester(self       )
						SCREAMING_SNAKE_CASE_   :	List[Any]													=   ConfigTester(self ,    config_class=UpperCAmelCase__       )


		def   __snake_case			(						self       ):
						self.config_tester.run_common_tests()






		def   __snake_case			(						self       ):
						SCREAMING_SNAKE_CASE_   :	int													=   self.model_tester.prepare_config_and_inputs_for_common()
						self.model_tester.check_decoder_model_past_large_inputs(*UpperCAmelCase__       )






@require_tokenizers
@require_tf
class 							__a							(  unittest.TestCase						):





		'''simple docstring'''



		UpperCAmelCase__      :				Optional[Any]				    =						[
		    """Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like """
		    """  i\'m going to throw up.\nand why is that?"""
		]
		UpperCAmelCase__      :				List[str]				    =						"""facebook/blenderbot_small-90M"""


		@cached_property
		def   __snake_case			(						self       ):
						return BlenderbotSmallTokenizer.from_pretrained('facebook/blenderbot-90M'       )


		@cached_property
		def   __snake_case			(						self       ):
						SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name       )
						return model






		@slow
		def   __snake_case			(						self       ):
						SCREAMING_SNAKE_CASE_   :	int													=   self.tokenizer(self.src_text ,    return_tensors='tf'       )
						SCREAMING_SNAKE_CASE_   :	Optional[int]													=   self.model.generate(
						    model_inputs.input_ids ,    attention_mask=model_inputs.attention_mask ,    num_beams=2 ,    use_cache=UpperCAmelCase__ ,    )
						SCREAMING_SNAKE_CASE_   :	str													=   self.tokenizer.batch_decode(generated_ids.numpy() ,    skip_special_tokens=UpperCAmelCase__       )[0]
						assert generated_words in (
						    "i don't know. i just feel like i'm going to throw up. it's not fun.",
						    "i'm not sure. i just feel like i've been feeling like i have to be in a certain place",
						    "i'm not sure. i just feel like i've been in a bad situation.",
						)







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


class 							__a							(  __A						):





		'''simple docstring'''



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


		def   __snake_case			(						self       ):
						SCREAMING_SNAKE_CASE_   :	Tuple													=   0
						SCREAMING_SNAKE_CASE_   :	Dict													=   False
						while not completed:
										if counter == 1:
														self.reset()
										SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   self.advance()
										if not self.does_advance(UpperCamelCase__       ):
														raise Exception(
														    'Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.'       )

										SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_   :	Any													=   self.update(UpperCamelCase__       )
										counter += 1

										if counter > 10000:
														raise Exception('update() does not fulfill the constraint.'       )

						if self.remaining() != 0:
										raise Exception('Custom Constraint is not defined correctly.'       )


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


		@abstractmethod
		def   __snake_case			(						self ,    UpperCamelCase__       ):
						raise NotImplementedError(
						    F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''       )


		@abstractmethod
		def   __snake_case			(						self ,    UpperCamelCase__       ):
						raise NotImplementedError(
						    F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''       )


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


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






		@abstractmethod
		def   __snake_case			(						self ,    UpperCamelCase__=False       ):
						raise NotImplementedError(
						    F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''       )






class 							__a							(  __A						):





		'''simple docstring'''



		def __init__(						self ,    UpperCamelCase__       ):
						super(UpperCamelCase__ ,    self       ).__init__()

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

						SCREAMING_SNAKE_CASE_   :	List[str]													=   token_ids

						SCREAMING_SNAKE_CASE_   :	Tuple													=   len(self.token_ids       )
						SCREAMING_SNAKE_CASE_   :	Any													=   -1  # the index of the currently fulfilled step
						SCREAMING_SNAKE_CASE_   :	Any													=   False


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


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

						if self.completed:
										return False

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


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

						SCREAMING_SNAKE_CASE_   :	Optional[int]													=   False
						SCREAMING_SNAKE_CASE_   :	Optional[int]													=   False
						SCREAMING_SNAKE_CASE_   :	List[Any]													=   False

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


		def   __snake_case			(						self       ):
						SCREAMING_SNAKE_CASE_   :	Optional[int]													=   False
						SCREAMING_SNAKE_CASE_   :	List[str]													=   0


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






		def   __snake_case			(						self ,    UpperCamelCase__=False       ):
						SCREAMING_SNAKE_CASE_   :	str													=   PhrasalConstraint(self.token_ids       )

						if stateful:
										SCREAMING_SNAKE_CASE_   :	List[Any]													=   self.seqlen
										SCREAMING_SNAKE_CASE_   :	Any													=   self.fulfilled_idx
										SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   self.completed

						return new_constraint






class 							__a							:





		'''simple docstring'''



		def __init__(						self ,    UpperCamelCase__ ,    UpperCamelCase__=True       ):
						SCREAMING_SNAKE_CASE_   :	Optional[int]													=   max([len(UpperCamelCase__       ) for one in nested_token_ids]       )

						SCREAMING_SNAKE_CASE_   :	List[Any]													=   {}
						for token_ids in nested_token_ids:
										SCREAMING_SNAKE_CASE_   :	Dict													=   root
										for tidx, token_id in enumerate(UpperCamelCase__       ):
														if token_id not in level:
																		SCREAMING_SNAKE_CASE_   :	Tuple													=   {}

														SCREAMING_SNAKE_CASE_   :	List[str]													=   level[token_id]

						if no_subsets and self.has_subsets(UpperCamelCase__ ,    UpperCamelCase__       ):
										raise ValueError(
										    'Each list in `nested_token_ids` can\'t be a complete subset of another list, but is'
										    F''' {nested_token_ids}.'''       )

						SCREAMING_SNAKE_CASE_   :	Tuple													=   root


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						SCREAMING_SNAKE_CASE_   :	int													=   self.trie

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

						SCREAMING_SNAKE_CASE_   :	Optional[int]													=   list(start.keys()       )

						return next_tokens


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						SCREAMING_SNAKE_CASE_   :	List[Any]													=   self.next_tokens(UpperCamelCase__       )

						return len(UpperCamelCase__       ) == 0


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						SCREAMING_SNAKE_CASE_   :	List[str]													=   list(root.values()       )
						if len(UpperCamelCase__       ) == 0:
										return 1
						else:
										return sum([self.count_leaves(UpperCamelCase__       ) for nn in next_nodes]       )






		def   __snake_case			(						self ,    UpperCamelCase__ ,    UpperCamelCase__       ):
						SCREAMING_SNAKE_CASE_   :	Dict													=   self.count_leaves(UpperCamelCase__       )
						return len(UpperCamelCase__       ) != leaf_count






class 							__a							(  __A						):





		'''simple docstring'''



		def __init__(						self ,    UpperCamelCase__       ):
						super(UpperCamelCase__ ,    self       ).__init__()

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

						SCREAMING_SNAKE_CASE_   :	Optional[int]													=   DisjunctiveTrie(UpperCamelCase__       )
						SCREAMING_SNAKE_CASE_   :	Dict													=   nested_token_ids

						SCREAMING_SNAKE_CASE_   :	List[str]													=   self.trie.max_height
						SCREAMING_SNAKE_CASE_   :	str													=   []
						SCREAMING_SNAKE_CASE_   :	List[str]													=   False


		def   __snake_case			(						self       ):
						SCREAMING_SNAKE_CASE_   :	List[str]													=   self.trie.next_tokens(self.current_seq       )

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


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						if not isinstance(UpperCamelCase__ ,    UpperCamelCase__       ):
										raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(UpperCamelCase__       )}'''       )

						SCREAMING_SNAKE_CASE_   :	str													=   self.trie.next_tokens(self.current_seq       )

						return token_id in next_tokens


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						if not isinstance(UpperCamelCase__ ,    UpperCamelCase__       ):
										raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(UpperCamelCase__       )}'''       )

						SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   False
						SCREAMING_SNAKE_CASE_   :	Tuple													=   False
						SCREAMING_SNAKE_CASE_   :	Dict													=   False

						if self.does_advance(UpperCamelCase__       ):
										self.current_seq.append(UpperCamelCase__       )
										SCREAMING_SNAKE_CASE_   :	int													=   True
						else:
										SCREAMING_SNAKE_CASE_   :	Tuple													=   True
										self.reset()

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

						return stepped, completed, reset


		def   __snake_case			(						self       ):
						SCREAMING_SNAKE_CASE_   :	List[Any]													=   False
						SCREAMING_SNAKE_CASE_   :	Dict													=   []


		def   __snake_case			(						self       ):
						if self.completed:
										# since this can be completed without reaching max height
										return 0
						else:
										return self.seqlen - len(self.current_seq       )






		def   __snake_case			(						self ,    UpperCamelCase__=False       ):
						SCREAMING_SNAKE_CASE_   :	Any													=   DisjunctiveConstraint(self.token_ids       )

						if stateful:
										SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   self.seqlen
										SCREAMING_SNAKE_CASE_   :	Optional[int]													=   self.current_seq
										SCREAMING_SNAKE_CASE_   :	List[str]													=   self.completed

						return new_constraint






class 							__a							:





		'''simple docstring'''



		def __init__(						self ,    UpperCamelCase__       ):
						SCREAMING_SNAKE_CASE_   :	Any													=   constraints

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

						self.init_state()


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


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

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


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						self.init_state()

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

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


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

						SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_   :	Dict													=   False, False

						if self.completed:
										SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   True
										SCREAMING_SNAKE_CASE_   :	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

										SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_   :	Dict													=   self.inprogress_constraint.update(UpperCamelCase__       )
										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=UpperCamelCase__       )       )
														SCREAMING_SNAKE_CASE_   :	Dict													=   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       )
														SCREAMING_SNAKE_CASE_   :	str													=   None

														if len(self.pending_constraints       ) == 0:
																		# we're done!
																		SCREAMING_SNAKE_CASE_   :	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(UpperCamelCase__       ):
																		SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_   :	Dict													=   pending_constraint.update(UpperCamelCase__       )

																		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(UpperCamelCase__       )
																						SCREAMING_SNAKE_CASE_   :	List[str]													=   None

																		if not complete and stepped:
																						SCREAMING_SNAKE_CASE_   :	List[str]													=   pending_constraint

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

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

																										SCREAMING_SNAKE_CASE_   :	Dict													=   True

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

						return complete, stepped






		def   __snake_case			(						self ,    UpperCamelCase__=True       ):
						SCREAMING_SNAKE_CASE_   :	Tuple													=   ConstraintListState(self.constraints       )  # we actually never though self.constraints objects
						# throughout this process. So it's at initialization state.

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

						return new_state