






import copy
import inspect
import unittest

from transformers import PretrainedConfig, SwiftFormerConfig
from transformers.testing_utils import (
    require_torch,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch
				from torch import nn

				from transformers import SwiftFormerForImageClassification, SwiftFormerModel
				from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
				from PIL import Image

				from transformers import ViTImageProcessor



class 		_snake_case  :






			def __init__(       self		,					a		,					a=13		,					a=3		,					a=True		,					a=True		,					a=0.1		,					a=0.1		,					a=224		,					a=1000		,					a=[3, 3, 6, 4]		,					a=[48, 56, 112, 220]		,					)      ->       Tuple:
						SCREAMING_SNAKE_CASE						= parent
						SCREAMING_SNAKE_CASE						= batch_size
						SCREAMING_SNAKE_CASE						= num_channels
						SCREAMING_SNAKE_CASE						= is_training
						SCREAMING_SNAKE_CASE						= use_labels
						SCREAMING_SNAKE_CASE						= hidden_dropout_prob
						SCREAMING_SNAKE_CASE						= attention_probs_dropout_prob
						SCREAMING_SNAKE_CASE						= num_labels
						SCREAMING_SNAKE_CASE						= image_size
						SCREAMING_SNAKE_CASE						= layer_depths
						SCREAMING_SNAKE_CASE						= embed_dims






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Any:
						SCREAMING_SNAKE_CASE						= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

						SCREAMING_SNAKE_CASE						= None
						if self.use_labels:
									SCREAMING_SNAKE_CASE						= ids_tensor([self.batch_size]		,					self.num_labels)

						SCREAMING_SNAKE_CASE						= self.get_config()

						return config, pixel_values, labels






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Tuple:
						return SwiftFormerConfig(
						    depths=self.layer_depths		,					embed_dims=self.embed_dims		,					mlp_ratio=4		,					downsamples=[True, True, True, True]		,					hidden_act='gelu'		,					num_labels=self.num_labels		,					down_patch_size=3		,					down_stride=2		,					down_pad=1		,					drop_rate=0.0		,					drop_path_rate=0.0		,					use_layer_scale=a		,					layer_scale_init_value=1E-5		,					)






			def    SCREAMING_SNAKE_CASE__    (       self		,					a		,					a		,					a)      ->       Any:
						SCREAMING_SNAKE_CASE						= SwiftFormerModel(config=a)
						model.to(a)
						model.eval()
						SCREAMING_SNAKE_CASE						= model(a)
						self.parent.assertEqual(result.last_hidden_state.shape		,					(self.batch_size, self.embed_dims[-1], 7, 7))






			def    SCREAMING_SNAKE_CASE__    (       self		,					a		,					a		,					a)      ->       int:
						SCREAMING_SNAKE_CASE						= self.num_labels
						SCREAMING_SNAKE_CASE						= SwiftFormerForImageClassification(a)
						model.to(a)
						model.eval()
						SCREAMING_SNAKE_CASE						= model(a		,					labels=a)
						self.parent.assertEqual(result.logits.shape		,					(self.batch_size, self.num_labels))

						SCREAMING_SNAKE_CASE						= SwiftFormerForImageClassification(a)
						model.to(a)
						model.eval()

						SCREAMING_SNAKE_CASE						= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
						SCREAMING_SNAKE_CASE						= model(a)
						self.parent.assertEqual(result.logits.shape		,					(self.batch_size, self.num_labels))







			def    SCREAMING_SNAKE_CASE__    (       self)      ->       int:
						((SCREAMING_SNAKE_CASE)				,						(SCREAMING_SNAKE_CASE)				,						(SCREAMING_SNAKE_CASE))						= self.prepare_config_and_inputs()
						SCREAMING_SNAKE_CASE						= {'pixel_values': pixel_values}
						return config, inputs_dict



@require_torch
class 		_snake_case  (  A__   ,    A__   ,    unittest.TestCase					):
			_lowercase		:    Dict			     =							(SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else ()
			_lowercase		:    Optional[int]			     =							(
			    {'''feature-extraction''': SwiftFormerModel, '''image-classification''': SwiftFormerForImageClassification}
			    if is_torch_available()
			    else {}
			)

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






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       List[str]:
						SCREAMING_SNAKE_CASE						= SwiftFormerModelTester(self)
						SCREAMING_SNAKE_CASE						= ConfigTester(
						    self		,					config_class=a		,					has_text_modality=a		,					hidden_size=37		,					num_attention_heads=12		,					num_hidden_layers=12		,					)






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       List[str]:
						self.config_tester.run_common_tests()






			@unittest.skip(reason='SwiftFormer does not use inputs_embeds')
			def    SCREAMING_SNAKE_CASE__    (       self)      ->       List[str]:
						pass






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Dict:
						SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						= self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
									SCREAMING_SNAKE_CASE						= model_class(a)
									SCREAMING_SNAKE_CASE						= model.get_output_embeddings()
									self.assertTrue(x is None or isinstance(a		,					nn.Linear))






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       List[str]:
						SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						= self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
									SCREAMING_SNAKE_CASE						= model_class(a)
									SCREAMING_SNAKE_CASE						= inspect.signature(model.forward)
									# signature.parameters is an OrderedDict => so arg_names order is deterministic
									SCREAMING_SNAKE_CASE						= [*signature.parameters.keys()]

									SCREAMING_SNAKE_CASE						= ['pixel_values']
									self.assertListEqual(arg_names[:1]		,					a)






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       List[str]:
						SCREAMING_SNAKE_CASE						= self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*a)






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Tuple:
						SCREAMING_SNAKE_CASE						= self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*a)






			@slow
			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Dict:
						for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									SCREAMING_SNAKE_CASE						= SwiftFormerModel.from_pretrained(a)
									self.assertIsNotNone(a)






			@unittest.skip(reason='SwiftFormer does not output attentions')
			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Any:
						pass






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Tuple:
						def check_hidden_states_output(a		,					a		,					a):
									SCREAMING_SNAKE_CASE						= model_class(a)
									model.to(a)
									model.eval()

									with torch.no_grad():
												SCREAMING_SNAKE_CASE						= model(**self._prepare_for_class(a		,					a))

									SCREAMING_SNAKE_CASE						= outputs.hidden_states

									SCREAMING_SNAKE_CASE						= 8
									self.assertEqual(len(a)		,					a)  # TODO

									# SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width)
									# with the width and height being successively divided by 2, after every 2 blocks
									for i in range(len(a)):
												self.assertEqual(
												    hidden_states[i].shape		,					torch.Size(
												        [
												            self.model_tester.batch_size,
												            self.model_tester.embed_dims[i // 2],
												            (self.model_tester.image_size // 4) // 2 ** (i // 2),
												            (self.model_tester.image_size // 4) // 2 ** (i // 2),
												        ])		,					)

						SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						= self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
									SCREAMING_SNAKE_CASE						= True
									check_hidden_states_output(a		,					a		,					a)

									# check that output_hidden_states also work using config
									del inputs_dict["output_hidden_states"]
									SCREAMING_SNAKE_CASE						= True

									check_hidden_states_output(a		,					a		,					a)






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       List[str]:
						def _config_zero_init(a):
									SCREAMING_SNAKE_CASE						= copy.deepcopy(a)
									for key in configs_no_init.__dict__.keys():
												if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key:
															setattr(a		,					a		,					1E-10)
												if isinstance(getattr(a		,					a		,					a)		,					a):
															SCREAMING_SNAKE_CASE						= _config_zero_init(getattr(a		,					a))
															setattr(a		,					a		,					a)
									return configs_no_init

						SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						= self.model_tester.prepare_config_and_inputs_for_common()

						SCREAMING_SNAKE_CASE						= _config_zero_init(a)
						for model_class in self.all_model_classes:
									SCREAMING_SNAKE_CASE						= model_class(config=a)
									for name, param in model.named_parameters():
												if param.requires_grad:
															self.assertIn(
															    ((param.data.mean() * 1E9) / 1E9).round().item()		,					[0.0, 1.0]		,					msg=f'''Parameter {name} of model {model_class} seems not properly initialized'''		,					)







			@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.')
			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Dict:
						pass






def 				lowerCamelCase__				():
			SCREAMING_SNAKE_CASE						= Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
			return image







@require_torch
@require_vision
class 		_snake_case  (  unittest.TestCase					):






			@cached_property
			def    SCREAMING_SNAKE_CASE__    (       self)      ->       List[str]:
						return ViTImageProcessor.from_pretrained('MBZUAI/swiftformer-xs') if is_vision_available() else None







			@slow
			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Union[str, Any]:
						SCREAMING_SNAKE_CASE						= SwiftFormerForImageClassification.from_pretrained('MBZUAI/swiftformer-xs').to(a)

						SCREAMING_SNAKE_CASE						= self.default_image_processor
						SCREAMING_SNAKE_CASE						= prepare_img()
						SCREAMING_SNAKE_CASE						= image_processor(images=a		,					return_tensors='pt').to(a)

						# forward pass
						with torch.no_grad():
									SCREAMING_SNAKE_CASE						= model(**a)

						# verify the logits
						SCREAMING_SNAKE_CASE						= torch.Size((1, 1000))
						self.assertEqual(outputs.logits.shape		,					a)

						SCREAMING_SNAKE_CASE						= torch.tensor([[-2.17_03E00, 2.11_07E00, -2.08_11E00]]).to(a)
						self.assertTrue(torch.allclose(outputs.logits[0, :3]		,					a		,					atol=1E-4))












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

class 		_snake_case  (  A__					):






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






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Tuple:
						SCREAMING_SNAKE_CASE						= 0
						SCREAMING_SNAKE_CASE						= False
						while not completed:
									if counter == 1:
												self.reset()
									SCREAMING_SNAKE_CASE						= self.advance()
									if not self.does_advance(a):
												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						= self.update(a)
									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    SCREAMING_SNAKE_CASE__    (       self)      ->       Optional[int]:
						raise NotImplementedError(
						    f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''')






			@abstractmethod
			def    SCREAMING_SNAKE_CASE__    (       self		,					a)      ->       List[Any]:
						raise NotImplementedError(
						    f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''')






			@abstractmethod
			def    SCREAMING_SNAKE_CASE__    (       self		,					a)      ->       Dict:
						raise NotImplementedError(
						    f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''')






			@abstractmethod
			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Optional[int]:
						raise NotImplementedError(
						    f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''')






			@abstractmethod
			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Dict:
						raise NotImplementedError(
						    f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''')







			@abstractmethod
			def    SCREAMING_SNAKE_CASE__    (       self		,					a=False)      ->       int:
						raise NotImplementedError(
						    f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''')



class 		_snake_case  (  A__					):






			def __init__(       self		,					a)      ->       Dict:
						super(a		,					self).__init__()

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

						SCREAMING_SNAKE_CASE						= len(self.token_ids)
						SCREAMING_SNAKE_CASE						= -1  # the index of the currently fulfilled step
						SCREAMING_SNAKE_CASE						= False






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Optional[Any]:
						if self.completed:
									return None
						return self.token_ids[self.fulfilled_idx + 1]






			def    SCREAMING_SNAKE_CASE__    (       self		,					a)      ->       Any:
						if not isinstance(a		,					a):
									raise ValueError(f'''`token_id` has to be an `int`, but is {token_id} of type {type(a)}''')

						if self.completed:
									return False

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






			def    SCREAMING_SNAKE_CASE__    (       self		,					a)      ->       Optional[int]:
						if not isinstance(a		,					a):
									raise ValueError(f'''`token_id` has to be an `int`, but is {token_id} of type {type(a)}''')

						SCREAMING_SNAKE_CASE						= False
						SCREAMING_SNAKE_CASE						= False
						SCREAMING_SNAKE_CASE						= False

						if self.does_advance(a):
									self.fulfilled_idx += 1
									SCREAMING_SNAKE_CASE						= True
									if self.fulfilled_idx == (self.seqlen - 1):
												SCREAMING_SNAKE_CASE						= True
									SCREAMING_SNAKE_CASE						= completed
						else:
									# failed to make progress.
									SCREAMING_SNAKE_CASE						= True
									self.reset()
						return stepped, completed, reset






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Any:
						SCREAMING_SNAKE_CASE						= False
						SCREAMING_SNAKE_CASE						= 0






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







			def    SCREAMING_SNAKE_CASE__    (       self		,					a=False)      ->       int:
						SCREAMING_SNAKE_CASE						= PhrasalConstraint(self.token_ids)

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

						return new_constraint



class 		_snake_case  :






			def __init__(       self		,					a		,					a=True)      ->       Tuple:
						SCREAMING_SNAKE_CASE						= max([len(a) for one in nested_token_ids])

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

												SCREAMING_SNAKE_CASE						= level[token_id]

						if no_subsets and self.has_subsets(a		,					a):
									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						= root






			def    SCREAMING_SNAKE_CASE__    (       self		,					a)      ->       Union[str, Any]:
						SCREAMING_SNAKE_CASE						= self.trie

						for current_token in current_seq:
									SCREAMING_SNAKE_CASE						= start[current_token]

						SCREAMING_SNAKE_CASE						= list(start.keys())

						return next_tokens






			def    SCREAMING_SNAKE_CASE__    (       self		,					a)      ->       int:
						SCREAMING_SNAKE_CASE						= self.next_tokens(a)

						return len(a) == 0






			def    SCREAMING_SNAKE_CASE__    (       self		,					a)      ->       int:
						SCREAMING_SNAKE_CASE						= list(root.values())
						if len(a) == 0:
									return 1
						else:
									return sum([self.count_leaves(a) for nn in next_nodes])







			def    SCREAMING_SNAKE_CASE__    (       self		,					a		,					a)      ->       Optional[int]:
						SCREAMING_SNAKE_CASE						= self.count_leaves(a)
						return len(a) != leaf_count



class 		_snake_case  (  A__					):






			def __init__(       self		,					a)      ->       Dict:
						super(a		,					self).__init__()

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

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






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Optional[int]:
						SCREAMING_SNAKE_CASE						= self.trie.next_tokens(self.current_seq)

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






			def    SCREAMING_SNAKE_CASE__    (       self		,					a)      ->       List[str]:
						if not isinstance(a		,					a):
									raise ValueError(f'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(a)}''')

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

						return token_id in next_tokens






			def    SCREAMING_SNAKE_CASE__    (       self		,					a)      ->       List[Any]:
						if not isinstance(a		,					a):
									raise ValueError(f'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(a)}''')

						SCREAMING_SNAKE_CASE						= False
						SCREAMING_SNAKE_CASE						= False
						SCREAMING_SNAKE_CASE						= False

						if self.does_advance(a):
									self.current_seq.append(a)
									SCREAMING_SNAKE_CASE						= True
						else:
									SCREAMING_SNAKE_CASE						= True
									self.reset()

						SCREAMING_SNAKE_CASE						= self.trie.reached_leaf(self.current_seq)
						SCREAMING_SNAKE_CASE						= completed

						return stepped, completed, reset






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       List[Any]:
						SCREAMING_SNAKE_CASE						= False
						SCREAMING_SNAKE_CASE						= []






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Dict:
						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		,					a=False)      ->       Union[str, Any]:
						SCREAMING_SNAKE_CASE						= DisjunctiveConstraint(self.token_ids)

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

						return new_constraint



class 		_snake_case  :






			def __init__(       self		,					a)      ->       Union[str, Any]:
						SCREAMING_SNAKE_CASE						= constraints

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

						self.init_state()






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Optional[int]:
						SCREAMING_SNAKE_CASE						= []
						SCREAMING_SNAKE_CASE						= None
						SCREAMING_SNAKE_CASE						= [constraint.copy(stateful=a) for constraint in self.constraints]






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

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






			def    SCREAMING_SNAKE_CASE__    (       self		,					a)      ->       int:
						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						= self.add(a)

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






			def    SCREAMING_SNAKE_CASE__    (       self		,					a)      ->       Union[str, Any]:
						if not isinstance(a		,					a):
									raise ValueError(f'''`token_id` should be an `int`, but is `{token_id}`.''')

						SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						= False, False

						if self.completed:
									SCREAMING_SNAKE_CASE						= True
									SCREAMING_SNAKE_CASE						= 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						= self.inprogress_constraint.update(a)
									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=a))
												SCREAMING_SNAKE_CASE						= 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						= None

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

															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(a)
																		SCREAMING_SNAKE_CASE						= None

															if not complete and stepped:
																		SCREAMING_SNAKE_CASE						= 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						= (
																		    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						= True

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

						return complete, stepped







			def    SCREAMING_SNAKE_CASE__    (       self		,					a=True)      ->       str:
						SCREAMING_SNAKE_CASE						= ConstraintListState(self.constraints)  # we actually never though self.constraints objects
						# throughout this process. So it's at initialization state.

						if stateful:
									SCREAMING_SNAKE_CASE						= [
									    constraint.copy(stateful=a) for constraint in self.complete_constraints
									]
									if self.inprogress_constraint is not None:
												SCREAMING_SNAKE_CASE						= self.inprogress_constraint.copy(stateful=a)
									SCREAMING_SNAKE_CASE						= [constraint.copy() for constraint in self.pending_constraints]

						return new_state




